Skip to content

Instantly share code, notes, and snippets.

@Tetsuya3850
Last active March 31, 2018 02:35
Show Gist options
  • Save Tetsuya3850/4cb1d002864fbf8f880b5eebc393b72a to your computer and use it in GitHub Desktop.
Save Tetsuya3850/4cb1d002864fbf8f880b5eebc393b72a to your computer and use it in GitHub Desktop.
Rabin-Karp Substring Search with Python
def rapin_karp(pat, txt):
M = len(pat)
N = len(txt)
p = 0
t = 0
h = 1
d = 256
q = 101
for i in range(M - 1):
h = (h * d) % q
for i in range(M):
p = (d * p + ord(pat[i])) % q
t = (d * t + ord(txt[i])) % q
for i in range(N - M + 1):
if p == t:
for j in range(M):
if txt[i + j] != pat[j]:
break
if j == M - 1:
print ("Pattern found at index " + str(i))
if i < N - M:
t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q
if t < 0:
t = t + q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment