11import numpy as np
22from numpy .fft import fft , ifft
33
4+
45def preprocess_text_and_pattern (text : str , pattern : str ) -> tuple [list [int ], list [int ]]:
56 """Preprocesses text and pattern for pattern matching.
67
@@ -13,11 +14,14 @@ def preprocess_text_and_pattern(text: str, pattern: str) -> tuple[list[int], lis
1314 - A list of integers representing the text characters.
1415 - A list of integers representing the pattern characters, with 0 for wildcards.
1516 """
17+
1618 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
1822
1923 # 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 ]
2125 text_int = [char_to_int [char ] for char in text ]
2226
2327 return text_int , pattern_int
@@ -37,6 +41,12 @@ def fft_convolution(a: list[int], b: list[int]) -> np.ndarray:
3741 b_fft = fft (b , n )
3842 return np .real (ifft (a_fft * b_fft ))
3943
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+
4050def compute_a_fft (text_int : list [int ], pattern_int : list [int ]) -> np .ndarray :
4151 """Computes the A array for the pattern matching algorithm.
4252
@@ -47,6 +57,7 @@ def compute_a_fft(text_int: list[int], pattern_int: list[int]) -> np.ndarray:
4757 Returns:
4858 The A array.
4959 """
60+
5061 n = len (text_int )
5162 m = len (pattern_int )
5263
@@ -66,9 +77,12 @@ def compute_a_fft(text_int: list[int], pattern_int: list[int]) -> np.ndarray:
6677
6778 # Calculate a[i] using the convolution results
6879 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 ]
6982
7083 return a
7184
85+
7286# Main function to run the matching
7387if __name__ == "__main__" :
7488 # Example test case
0 commit comments