2019-02-23 14:18:21 +00:00
|
|
|
"""
|
2020-06-01 13:40:40 +00:00
|
|
|
https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
|
2019-02-23 14:18:21 +00:00
|
|
|
this algorithm tries to find the pattern from every position of
|
|
|
|
the mainString if pattern is found from position i it add it to
|
|
|
|
the answer and does the same for position i+1
|
|
|
|
Complexity : O(n*m)
|
|
|
|
n=length of main string
|
|
|
|
m=length of pattern string
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2020-06-01 13:40:40 +00:00
|
|
|
def naive_pattern_search(s: str, pattern: str) -> list:
|
|
|
|
"""
|
|
|
|
>>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")
|
|
|
|
[4, 10, 18]
|
|
|
|
>>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")
|
|
|
|
[]
|
|
|
|
>>> naive_pattern_search("", "ABC")
|
|
|
|
[]
|
|
|
|
>>> naive_pattern_search("TEST", "TEST")
|
|
|
|
[0]
|
|
|
|
>>> naive_pattern_search("ABCDEGFTEST", "TEST")
|
|
|
|
[7]
|
|
|
|
"""
|
|
|
|
pat_len = len(pattern)
|
2019-10-05 05:14:13 +00:00
|
|
|
position = []
|
2020-06-01 13:40:40 +00:00
|
|
|
for i in range(len(s) - pat_len + 1):
|
2019-10-05 05:14:13 +00:00
|
|
|
match_found = True
|
2020-06-01 13:40:40 +00:00
|
|
|
for j in range(pat_len):
|
|
|
|
if s[i + j] != pattern[j]:
|
2019-10-05 05:14:13 +00:00
|
|
|
match_found = False
|
2019-02-23 14:18:21 +00:00
|
|
|
break
|
|
|
|
if match_found:
|
|
|
|
position.append(i)
|
|
|
|
return position
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2020-06-01 13:40:40 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
assert naive_pattern_search("ABCDEFG", "DE") == [3]
|
2021-08-13 07:10:52 +00:00
|
|
|
print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
|