Skip to content

Commit 161350a

Browse files
committed
KMP.py finally approved
1 parent b561e93 commit 161350a

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

  • DataStructures/Section12

DataStructures/Section12/KMP.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#String matching by KMP algorithm
2+
3+
def pfun(pattern):
4+
n = len(pattern)
5+
prefix_fun = [0]*(n)
6+
7+
k = 0
8+
for q in range(2, n):
9+
while k>0 and pattern[k + 1] != pattern[q]:
10+
k = prefix_fun[k]
11+
if pattern[k + 1] == pattern[q]:
12+
k += 1
13+
prefix_fun[q] = k
14+
return prefix_fun
15+
16+
17+
def KMP_Matcher(text, pattern):
18+
m = len(text)
19+
n = len(pattern)
20+
flag = False
21+
text = '-' + text
22+
pattern = '-' + pattern
23+
prefix_fun = pfun(pattern)
24+
q = 0
25+
26+
for i in range(1, m+1):
27+
while q > 0 and pattern[q + 1] != text[i]:
28+
q = prefix_fun[q]
29+
if pattern[q + 1] == text[i]:
30+
q += 1
31+
if q == n:
32+
print("Pattern occurs at positions ",i-n) # print the index, where first match occurs.
33+
flag = True
34+
q = prefix_fun[q]
35+
if not flag:
36+
print('\nNo match found')
37+
38+
39+
#Output of KMP algorithm
40+
KMP_Matcher('aabaacaadaabaaba','aabaa')

0 commit comments

Comments
 (0)