Skip to content

Commit

Permalink
Update Python implementation for the Rabin Karp algorithm.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Amitsharma45 authored Apr 7, 2020
1 parent 4cbf6d0 commit 6fae0ca
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions Python implementation for the Rabin Karp algorithm.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

d = 256
def search(pat, txt, q):
M = len(pat)
Expand All @@ -7,13 +8,19 @@ def search(pat, txt, q):
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
Expand All @@ -24,10 +31,15 @@ def search(pat, txt, q):
t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q
if t < 0:
t = t + q

# Taking input from user text and pattern
txt = input("Enter text\n")
pat = input("Enter pattern\n")
q = 101
search(pat, txt, q)
q = 101
#calling the function
search(pat, txt, q)


# This code is contributed by Amit sharma
'''
test 1
Expand Down

0 comments on commit 6fae0ca

Please sign in to comment.