From 1a254465e38b45ce3ed6919054b1113cf51137d9 Mon Sep 17 00:00:00 2001 From: mateuszz0000 Date: Mon, 1 Jun 2020 15:40:40 +0200 Subject: [PATCH] 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 --- strings/naive_string_search.py | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/strings/naive_string_search.py b/strings/naive_string_search.py index a8c2ea584..f28950264 100644 --- a/strings/naive_string_search.py +++ b/strings/naive_string_search.py @@ -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 @@ -9,14 +11,25 @@ Complexity : O(n*m) """ -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: @@ -24,9 +37,6 @@ def naivePatternSearch(mainString, pattern): 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') = }")