Skip to content

Naive string doctests + typehints #2054

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 1, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions strings/naive_string_search.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""
https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search

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
Expand All @@ -9,24 +11,32 @@
"""


def naivePatternSearch(mainString, pattern):
patLen = len(pattern)
strLen = len(mainString)
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)
position = []
for i in range(strLen - patLen + 1):
for i in range(len(s) - pat_len + 1):
match_found = True
for j in range(patLen):
if mainString[i + j] != pattern[j]:
for j in range(pat_len):
if s[i + j] != pattern[j]:
match_found = False
break
if match_found:
position.append(i)
return position


mainString = "ABAAABCDBBABCDDEBCABC"
pattern = "ABC"
position = naivePatternSearch(mainString, pattern)
print("Pattern found in position ")
for x in position:
print(x)
if __name__ == "__main__":
assert naive_pattern_search("ABCDEFG", "DE") == [3]
print(f"{naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC') = }")