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)
| 1 | def 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 | |
| 36 | def get_failure_array(pattern): |
no test coverage detected