Skip to content

Instantly share code, notes, and snippets.

@inside-code-yt
Created September 24, 2022 13:15
Show Gist options
  • Save inside-code-yt/66b373f02e358b0d21c485b3117bf8d1 to your computer and use it in GitHub Desktop.
Save inside-code-yt/66b373f02e358b0d21c485b3117bf8d1 to your computer and use it in GitHub Desktop.
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