Created
January 16, 2014 21:51
-
-
Save zpconn/8464137 to your computer and use it in GitHub Desktop.
A simple implementation of the Rabin-Karp substring search algorithm with a fairly naive running hash function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RollingHash: | |
s = None | |
start = 0 | |
end = 0 | |
hash = 0 | |
def __init__(self, s, length): | |
self.s = s | |
self.end = length - 1 | |
for i in range(length): | |
self.hash += ord(s[i]) | |
def update(self): | |
if self.s is None: | |
return | |
self.hash -= ord(self.s[self.start]) | |
self.start += 1 | |
self.end += 1 | |
if self.end <= len(self.s) - 1: | |
self.hash += ord(self.s[self.end]) | |
def search(s, ss): | |
if len(ss) > len(s): | |
return False | |
sshash = RollingHash(ss, len(ss)) | |
shash = RollingHash(s, len(ss)) | |
while shash.end <= len(s) - 1: | |
if sshash.hash == shash.hash: | |
if ss == s[shash.start:(shash.end + 1)]: | |
return True | |
shash.update() | |
return False | |
print search("Hello, world", "o, w") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment