Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. class RollingHash:
  2. def __init__(self, text, sizeWord):
  3. self.text = text
  4. self.hash = 0
  5. self.sizeWord = sizeWord
  6.  
  7. for i in range(0, sizeWord):
  8. #subtract out the ASCII value of "a" to start the indexing at zero
  9. self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(sizeWord - i -1))
  10. #start index of current window
  11. self.window_start = 0
  12. #end of index window
  13. self.window_end = sizeWord
  14.  
  15. def move_window(self):
  16. if self.window_end <= len(self.text) - 1:
  17.  
  18. self.hash -= (ord(self.text[self.window_start]) - ord("a")+1)*26**(self.sizeWord-1)
  19. self.hash *= 26
  20. self.hash += ord(self.text[self.window_end])- ord("a")+1
  21. self.window_start += 1
  22. self.window_end += 1
  23.  
  24. def window_text(self):
  25. return self.text[self.window_start:self.window_end]
  26.  
  27. def rabin_karp(word, text):
  28. if word == "" or text == "":
  29. return None
  30. if len(word) > len(text):
  31. return None
  32.  
  33. rolling_hash = RollingHash(text, len(word))
  34. word_hash = RollingHash(word, len(word))
  35. word_hash.move_window()
  36.  
  37. for i in range(len(text) - len(word) + 1):
  38. if rolling_hash.hash == word_hash.hash:
  39. if rolling_hash.window_text() == word:
  40. return i
  41. rolling_hash.move_window()
  42. return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement