Skip to content

Commit dc8aa5b

Browse files
Merge pull request #744 from ask2sm/patch-14
robbinkarpstringmatching.py
2 parents 207a2d9 + 6a9c447 commit dc8aa5b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Strings/robbinkarpstringmatching.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import math
2+
d = 256
3+
def search(pat, txt, q):
4+
M = len(pat)
5+
N = len(txt)
6+
p = 0
7+
t = 0
8+
h = pow(d,M-1)%q
9+
for i in range(M):
10+
p = (d*p + ord(pat[i]))%q
11+
t = (d*t + ord(txt[i]))%q
12+
for i in range(N-M+1):
13+
if p==t:
14+
for j in range(M):
15+
if txt[i+j] != pat[j]:
16+
break
17+
18+
j+=1
19+
if j==M:
20+
print ("Pattern found at index " ,i)
21+
if i < N-M:
22+
t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%q
23+
if t < 0:
24+
t = t+q
25+
txt = "Sourav Mondal SM"
26+
pat = "SM"
27+
q = 101
28+
search(pat,txt,q)

0 commit comments

Comments
 (0)