Skip to content

Commit 276f46a

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent e7c0701 commit 276f46a

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

strings/wildcard_pattern_matching_fft.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import numpy as np
22
from numpy.fft import fft, ifft
33

4+
45
def preprocess_text_and_pattern(text, pattern):
56
"""Preprocesses text and pattern for pattern matching.
67
@@ -15,14 +16,17 @@ def preprocess_text_and_pattern(text, pattern):
1516
"""
1617

1718
unique_chars = set(text + pattern)
18-
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
1922

2023
# Replace pattern '*' with 0, other characters with their unique integers
21-
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]
2225
text_int = [char_to_int[char] for char in text]
2326

2427
return text_int, pattern_int
2528

29+
2630
def fft_convolution(a, b):
2731
"""Performs convolution using the Fast Fourier Transform (FFT).
2832
@@ -39,6 +43,7 @@ def fft_convolution(a, b):
3943
B = fft(b, n)
4044
return np.real(ifft(A * B))
4145

46+
4247
def compute_A_fft(text_int, pattern_int):
4348
"""Computes the A array for the pattern matching algorithm.
4449
@@ -68,14 +73,15 @@ def compute_A_fft(text_int, pattern_int):
6873
sum3 = fft_convolution(p1[::-1], t3)
6974

7075
# Calculate A[i] using the convolution results
71-
A = sum1[:n - m + 1] - 2 * sum2[:n - m + 1] + sum3[:n - m + 1]
76+
A = sum1[: n - m + 1] - 2 * sum2[: n - m + 1] + sum3[: n - m + 1]
7277

7378
return A
7479

80+
7581
# Main function to run the matching
7682
if __name__ == "__main__":
77-
7883
import doctest
84+
7985
doctest.testmod()
8086
# Get text and pattern as input from the user
8187
# text = input("Enter the text: ")
@@ -84,13 +90,9 @@ def compute_A_fft(text_int, pattern_int):
8490
text = "abcabc"
8591
pattern = "abc*"
8692

87-
88-
89-
9093
text_int, pattern_int = preprocess_text_and_pattern(text, pattern)
9194
A = compute_A_fft(text_int, pattern_int)
9295

9396
# Matches occur where A[i] == 0
9497
matches = [i for i in range(len(A)) if np.isclose(A[i], 0)]
9598
print("Pattern matches at indices:", matches)
96-

0 commit comments

Comments
 (0)