Skip to content

Commit 2d4b35b

Browse files
Merge pull request matthewsamuel95#608 from ngochai94/master
Add a Python implementation for the kmp algorithm
2 parents 2eb25bc + 0b5ba27 commit 2d4b35b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

String/KMP/kmp.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/env python2.7
2+
def get_kmp(xs):
3+
res = [-1, 0]
4+
cur = 0
5+
for i in range(2, len(xs) + 1):
6+
while cur >= 0 and xs[cur] != xs[i - 1]:
7+
cur = res[cur]
8+
cur += 1
9+
res.append(cur)
10+
return res
11+
12+
def find_pattern(text, pattern):
13+
kmp = get_kmp(pattern + ' ' + text)
14+
return [i for i in range(len(text) - len(pattern) + 1)
15+
if kmp[i + len(pattern) * 2 + 1] == len(pattern)]
16+
17+
18+
if __name__ == '__main__':
19+
text = raw_input("Input text: ")
20+
pattern = raw_input("Input pattern: ")
21+
print "Pattern appears at starting indices: ", find_pattern(text, pattern)

0 commit comments

Comments
 (0)