forked from AllAlgorithms/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabin_karp.py
More file actions
46 lines (34 loc) · 962 Bytes
/
Copy pathrabin_karp.py
File metadata and controls
46 lines (34 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/local/bin/env python3
# Rabin Karp Algorithm in python using hash values
# d is the number of characters in input alphabet
d = 2560
def search(pat, txt, q):
M = len(pat)
N = len(txt)
i = 0
j = 0
p = 0
t = 0
h = 1
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
j += 1
if j == M:
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
# Driver program to test the above function
txt = "ALL WORLDS IS A STAGE AND ALL OF US ARE A PART OF THE PLAY"
pat = "ALL"
q = 101 # A prime number
search(pat, txt, q)