Created
September 24, 2022 13:15
-
-
Save inside-code-yt/66b373f02e358b0d21c485b3117bf8d1 to your computer and use it in GitHub Desktop.
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
def rabin_karp(s, p, d=26, q=101): | |
n = len(s) | |
m = len(p) | |
h = pow(d, m-1) % q | |
hash_p = 0 | |
hash_s = 0 | |
output = [] | |
for i in range(m): | |
hash_p = (d*hash_p + ord(p[i])) % q | |
hash_s = (d*hash_s + ord(s[i])) % q | |
for i in range(n-m+1): | |
if hash_s == hash_p: | |
if s[i:i+m] == p: | |
output.append(i) | |
if i < n-m: | |
hash_s = (d*(hash_s-ord(s[i])*h)+ord(s[i+m])) % q | |
return output | |
s = "acaabacaaabaababcda" | |
p = "aaba" | |
print(rabin_karp(s, p)) | |
# Output: [2, 8, 11] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment