1
1
import numpy as np
2
2
from numpy .fft import fft , ifft
3
3
4
+
4
5
def preprocess_text_and_pattern (text : str , pattern : str ) -> tuple [list [int ], list [int ]]:
5
6
"""Preprocesses text and pattern for pattern matching.
6
7
@@ -13,11 +14,14 @@ def preprocess_text_and_pattern(text: str, pattern: str) -> tuple[list[int], lis
13
14
- A list of integers representing the text characters.
14
15
- A list of integers representing the pattern characters, with 0 for wildcards.
15
16
"""
17
+
16
18
unique_chars = set (text + pattern )
17
- char_to_int = {char : i + 1 for i , char in enumerate (unique_chars )} # Unique non-zero integers
19
+ char_to_int = {
20
+ char : i + 1 for i , char in enumerate (unique_chars )
21
+ } # Unique non-zero integers
18
22
19
23
# Replace pattern '*' with 0, other characters with their unique integers
20
- pattern_int = [char_to_int [char ] if char != '*' else 0 for char in pattern ]
24
+ pattern_int = [char_to_int [char ] if char != "*" else 0 for char in pattern ]
21
25
text_int = [char_to_int [char ] for char in text ]
22
26
23
27
return text_int , pattern_int
@@ -37,6 +41,12 @@ def fft_convolution(a: list[int], b: list[int]) -> np.ndarray:
37
41
b_fft = fft (b , n )
38
42
return np .real (ifft (a_fft * b_fft ))
39
43
44
+ n = len (input_seq_a ) + len (input_seq_b ) - 1
45
+ A = fft (input_seq_a , n )
46
+ B = fft (input_seq_b , n )
47
+ return np .real (ifft (A * B ))
48
+
49
+
40
50
def compute_a_fft (text_int : list [int ], pattern_int : list [int ]) -> np .ndarray :
41
51
"""Computes the A array for the pattern matching algorithm.
42
52
@@ -47,6 +57,7 @@ def compute_a_fft(text_int: list[int], pattern_int: list[int]) -> np.ndarray:
47
57
Returns:
48
58
The A array.
49
59
"""
60
+
50
61
n = len (text_int )
51
62
m = len (pattern_int )
52
63
@@ -66,9 +77,12 @@ def compute_a_fft(text_int: list[int], pattern_int: list[int]) -> np.ndarray:
66
77
67
78
# Calculate a[i] using the convolution results
68
79
a = sum1 [:n - m + 1 ] - 2 * sum2 [:n - m + 1 ] + sum3 [:n - m + 1 ]
80
+ # Calculate A[i] using the convolution results
81
+ A = sum1 [: n - m + 1 ] - 2 * sum2 [: n - m + 1 ] + sum3 [: n - m + 1 ]
69
82
70
83
return a
71
84
85
+
72
86
# Main function to run the matching
73
87
if __name__ == "__main__" :
74
88
# Example test case
0 commit comments