-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkmp__pattern_search.py
54 lines (40 loc) · 1.12 KB
/
kmp__pattern_search.py
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
47
48
49
50
51
52
53
54
import os, sys, warnings
def find_all(pattern, text):
m = len(pattern)
n = len(text)
pos=[]
lps=[0]
roll_back_ind = 0
i=1
'''Make Longest Proper prefix table'''
while i < m:
if pattern[i] == pattern[roll_back_ind]:
roll_back_ind+=1
lps.append(roll_back_ind)
i += 1
elif pattern[i] is not pattern[roll_back_ind] and roll_back_ind > 0:
roll_back_ind = lps[roll_back_ind-1]
elif roll_back_ind==0:
lps.append(0)
i += 1
i=j=0
while i < n:
if text[i] == pattern[j]:
i,j = i+1, j+1
if j == m:
pos.append(i-m)
j = lps[m-1]
elif text[i] is not pattern[j]:
if j > 0:
j = lps[j-1]
else:
i = i+1
return pos
if __name__=='__main__':
with open('../../TEST_DATA/LOREM_IPSUM.txt') as f:
t = f.read()
p='ipsum'
ind = find_all(pattern=p, text=t)
print(ind)
for i in ind:
print(t[i-2:i+len(p)+2])