Skip to content

Commit 8149be5

Browse files
[Documentation] knuth_morris_pratt (#835)
* attach documentation to method; add annotations * add test case for list of integers Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
1 parent 87eae9a commit 8149be5

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

algorithms/strings/knuth_morris_pratt.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
1-
"""
2-
Given two strings text and pattern,
3-
return the list of start indexes in text that matches with the pattern
4-
using knuth_morris_pratt algorithm.
5-
If idx is in the list, text[idx : idx + M] matches with pattern.
6-
Time complexity : O(N+M)
7-
N and M is the length of text and pattern, respectively.
8-
"""
1+
from typing import Sequence, List
92

10-
def knuth_morris_pratt(text, pattern):
3+
def knuth_morris_pratt(text : Sequence, pattern : Sequence) -> List[int]:
4+
"""
5+
Given two strings text and pattern, return the list of start indexes in text that matches with the pattern
6+
using knuth_morris_pratt algorithm.
7+
8+
Args:
9+
text: Text to search
10+
pattern: Pattern to search in the text
11+
Returns:
12+
List of indices of patterns found
13+
14+
Example:
15+
>>> knuth_morris_pratt('hello there hero!', 'he')
16+
[0, 7, 12]
17+
18+
If idx is in the list, text[idx : idx + M] matches with pattern.
19+
Time complexity of the algorithm is O(N+M), with N and M the length of text and pattern, respectively.
20+
"""
1121
n = len(text)
1222
m = len(pattern)
1323
pi = [0 for i in range(m)]

tests/test_strings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,7 @@ def test_knuth_morris_pratt(self):
610610
self.assertEqual([0, 1, 2, 3, 4], knuth_morris_pratt("aaaaaaa", "aaa"))
611611
self.assertEqual([0, 4], knuth_morris_pratt("abcdabc", "abc"))
612612
self.assertEqual([], knuth_morris_pratt("aabcdaab", "aba"))
613+
self.assertEqual([0, 4], knuth_morris_pratt([0,0,1,1,0,0,1,0], [0,0]))
613614

614615

615616
class TestPanagram(unittest.TestCase):

0 commit comments

Comments
 (0)