t = 'haystack needle haystack' # "text" - thing we search in
p = 'needle' # "pattern" - thing we search for
def naive(p, t):
assert len(p) <= len(t) # assume text at least as long as pattern
occurrences = []
for i in range(len(t)-len(p)+1): # for each alignment of p to t
match = True # assume we match until proven wrong
for j in range(len(p)): # for each position of p
if t[i+j] != p[j]:
match = False # at least 1 char mismatches
break
if match:
occurrences.append(i)
return occurrences
naive(p, t)
[9]
t[9:9+len(p)] # confirm it really occurs
'needle'
naive('needle', 'needleneedleneedle')
[0, 6, 12]