MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / kmp

Function kmp

strings/knuth_morris_pratt.py:1–33  ·  view source on GitHub ↗

The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern

(pattern, text)

Source from the content-addressed store, hash-verified

1def kmp(pattern, text):
2 """
3 The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
4 with complexity O(n + m)
5
6 1) Preprocess pattern to identify any suffixes that are identical to prefixes
7
8 This tells us where to continue from if we get a mismatch between a character in our pattern
9 and the text.
10
11 2) Step through the text one character at a time and compare it to a character in the pattern
12 updating our location within the pattern if necessary
13
14 """
15
16 # 1) Construct the failure array
17 failure = get_failure_array(pattern)
18
19 # 2) Step through text searching for pattern
20 i, j = 0, 0 # index into text, pattern
21 while i < len(text):
22 if pattern[j] == text[i]:
23 if j == (len(pattern) - 1):
24 return True
25 j += 1
26
27 # if this is a prefix in our pattern
28 # just go back far enough to continue
29 elif j > 0:
30 j = failure[j - 1]
31 continue
32 i += 1
33 return False
34
35
36def get_failure_array(pattern):

Callers 1

Calls 1

get_failure_arrayFunction · 0.85

Tested by

no test coverage detected