Skip to content

Commit

Permalink
[Documentation] knuth_morris_pratt (keon#835)
Browse files Browse the repository at this point in the history
* attach documentation to method; add annotations

* add test case for list of integers

Co-authored-by: Pieter Eendebak <[email protected]>
  • Loading branch information
peendebak and eendebakpt authored Mar 2, 2022
1 parent 87eae9a commit 8149be5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
28 changes: 19 additions & 9 deletions algorithms/strings/knuth_morris_pratt.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
"""
Given two strings text and pattern,
return the list of start indexes in text that matches with the pattern
using knuth_morris_pratt algorithm.
If idx is in the list, text[idx : idx + M] matches with pattern.
Time complexity : O(N+M)
N and M is the length of text and pattern, respectively.
"""
from typing import Sequence, List

def knuth_morris_pratt(text, pattern):
def knuth_morris_pratt(text : Sequence, pattern : Sequence) -> List[int]:
"""
Given two strings text and pattern, return the list of start indexes in text that matches with the pattern
using knuth_morris_pratt algorithm.
Args:
text: Text to search
pattern: Pattern to search in the text
Returns:
List of indices of patterns found
Example:
>>> knuth_morris_pratt('hello there hero!', 'he')
[0, 7, 12]
If idx is in the list, text[idx : idx + M] matches with pattern.
Time complexity of the algorithm is O(N+M), with N and M the length of text and pattern, respectively.
"""
n = len(text)
m = len(pattern)
pi = [0 for i in range(m)]
Expand Down
1 change: 1 addition & 0 deletions tests/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,7 @@ def test_knuth_morris_pratt(self):
self.assertEqual([0, 1, 2, 3, 4], knuth_morris_pratt("aaaaaaa", "aaa"))
self.assertEqual([0, 4], knuth_morris_pratt("abcdabc", "abc"))
self.assertEqual([], knuth_morris_pratt("aabcdaab", "aba"))
self.assertEqual([0, 4], knuth_morris_pratt([0,0,1,1,0,0,1,0], [0,0]))


class TestPanagram(unittest.TestCase):
Expand Down

0 comments on commit 8149be5

Please sign in to comment.