Skip to content

Instantly share code, notes, and snippets.

@ronzhin-dmitry
Last active January 29, 2023 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronzhin-dmitry/f8afd9458b8f2f5ece450d763dd6f7f7 to your computer and use it in GitHub Desktop.
Save ronzhin-dmitry/f8afd9458b8f2f5ece450d763dd6f7f7 to your computer and use it in GitHub Desktop.
#Naive algorithm to search all the appearences of a substring inside string
def search_naive(needle, haystack): #Search for a needle (i.e. search request) inside a haystack (i.e. text where we search)
n = len(haystack)
k = len(needle)
result = []
for i in range(n-k+1): #this is actually just a sliding window approach
are_equal = True
for j in range(k):
are_equal = (haystack[i+j] == needle[j])
if not are_equal:
break
if are_equal:
result.append(i) #if we find an appearance we just add a position to results
return result
haystack = 'abbabcbabcbaabc' #consider this 'text' - haystack
needle = 'abc' #and this is a simple search request
search_naive(needle, haystack) #let's call for our naive search function
#Output is [3, 7, 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment