Skip to content
This repository has been archived by the owner on Nov 6, 2018. It is now read-only.

Commit

Permalink
kmp_search can now find *all* indices, not just the first one
Browse files Browse the repository at this point in the history
  • Loading branch information
jabagawee committed Oct 3, 2012
1 parent 30fd54c commit a5dc90c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
18 changes: 10 additions & 8 deletions algorithms/searching/kmp_search.py
Expand Up @@ -15,28 +15,30 @@
Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed.
kmp_search.search(sorted_list) -> integer
kmp_search.search(sorted_list) -> False
kmp_search.search(sorted_list) -> list[integers]
kmp_search.search(sorted_list) -> list[empty]
"""


def search(string, word):
word_length = len(word)
prefix = compute_prefix(word)
q = 0
offsets = []
q = 0 # q is the number of characters matched
for i in xrange(len(string)):
while q > 0 and word[q] != string[i]:
q = prefix[q - 1]
q = prefix[q - 1] # next character does not match
if word[q] == string[i]:
q = q + 1
q += 1
if q == word_length:
return i - word_length + 1
return False
offsets.append(i - word_length + 1)
q = prefix[q - 1] # look for next match
return offsets


def compute_prefix(word):
word_length = len(word)
prefix = [0] * word_length
prefix = [0 for i in xrange(word_length)]
k = 0

for q in xrange(1, word_length):
Expand Down
2 changes: 1 addition & 1 deletion algorithms/tests/test_searching.py
Expand Up @@ -41,7 +41,7 @@ def test_kmpsearch(self):
self.string = "ABCDE FG ABCDEABCDEF"
rv1 = kmp_search.search(self.string, "ABCDEA")
rv2 = kmp_search.search(self.string, "ABCDER")
self.assertIs(rv1, 9)
self.assertIs(rv1[0], 9)
self.assertFalse(rv2)


Expand Down

0 comments on commit a5dc90c

Please sign in to comment.