Skip to content

Commit 1a25446

Browse files
l3str4ngecclauss
andauthored
Naive string doctests + typehints (#2054)
* Added doctests * Added __main__ * Commit suggestion * Undo changes to keep only doctests and typehints * Reundo function name with params * Update naive_string_search.py * Update naive_string_search.py * Update naive_string_search.py * Update naive_string_search.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 321b142 commit 1a25446

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

Diff for: strings/naive_string_search.py

+22-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
"""
2+
https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
3+
24
this algorithm tries to find the pattern from every position of
35
the mainString if pattern is found from position i it add it to
46
the answer and does the same for position i+1
@@ -9,24 +11,32 @@
911
"""
1012

1113

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)
1528
position = []
16-
for i in range(strLen - patLen + 1):
29+
for i in range(len(s) - pat_len + 1):
1730
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]:
2033
match_found = False
2134
break
2235
if match_found:
2336
position.append(i)
2437
return position
2538

2639

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

Comments
 (0)