-
Notifications
You must be signed in to change notification settings - Fork 0
/
fuzzy-match.py
39 lines (36 loc) · 1.06 KB
/
fuzzy-match.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def kmp_table(pattern):
"""Constructs the partial match table for KMP algorithm."""
table = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
if pattern[i] == pattern[j]:
j += 1
table[i] = j
else:
j = table[j-1]
while j > 0 and pattern[i] != pattern[j]:
j = table[j-1]
if pattern[i] == pattern[j]:
j += 1
table[i] = j
return table
def kmp_search(text, pattern):
"""Performs KMP string matching algorithm."""
table = kmp_table(pattern)
matches = []
j = 0
for i in range(len(text)):
while j > 0 and text[i] != pattern[j]:
j = table[j-1]
if text[i] == pattern[j]:
j += 1
if j == len(pattern):
matches.append(i - j + 1) # match found
j = table[j-1]
return matches
# Example usage:
text = "ABABDABACDABABCABAB"
pattern = "ABABCABAB"
matches = kmp_search(text, pattern)
# Output the result
print(f"The pattern was found at indices: {matches}")