|
1 | 1 | """
|
| 2 | +https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search |
| 3 | +
|
2 | 4 | this algorithm tries to find the pattern from every position of
|
3 | 5 | the mainString if pattern is found from position i it add it to
|
4 | 6 | the answer and does the same for position i+1
|
|
9 | 11 | """
|
10 | 12 |
|
11 | 13 |
|
12 |
| -def naivePatternSearch(mainString, pattern): |
13 |
| - patLen = len(pattern) |
14 |
| - strLen = len(mainString) |
| 14 | +def naive_pattern_search(s: str, pattern: str) -> list: |
| 15 | + """ |
| 16 | + >>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC") |
| 17 | + [4, 10, 18] |
| 18 | + >>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC") |
| 19 | + [] |
| 20 | + >>> naive_pattern_search("", "ABC") |
| 21 | + [] |
| 22 | + >>> naive_pattern_search("TEST", "TEST") |
| 23 | + [0] |
| 24 | + >>> naive_pattern_search("ABCDEGFTEST", "TEST") |
| 25 | + [7] |
| 26 | + """ |
| 27 | + pat_len = len(pattern) |
15 | 28 | position = []
|
16 |
| - for i in range(strLen - patLen + 1): |
| 29 | + for i in range(len(s) - pat_len + 1): |
17 | 30 | match_found = True
|
18 |
| - for j in range(patLen): |
19 |
| - if mainString[i + j] != pattern[j]: |
| 31 | + for j in range(pat_len): |
| 32 | + if s[i + j] != pattern[j]: |
20 | 33 | match_found = False
|
21 | 34 | break
|
22 | 35 | if match_found:
|
23 | 36 | position.append(i)
|
24 | 37 | return position
|
25 | 38 |
|
26 | 39 |
|
27 |
| -mainString = "ABAAABCDBBABCDDEBCABC" |
28 |
| -pattern = "ABC" |
29 |
| -position = naivePatternSearch(mainString, pattern) |
30 |
| -print("Pattern found in position ") |
31 |
| -for x in position: |
32 |
| - print(x) |
| 40 | +if __name__ == "__main__": |
| 41 | + assert naive_pattern_search("ABCDEFG", "DE") == [3] |
| 42 | + print(f"{naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC') = }") |
0 commit comments