Skip to content

Instantly share code, notes, and snippets.

@twaddington
Created June 1, 2011 04:53
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 twaddington/1001806 to your computer and use it in GitHub Desktop.
Save twaddington/1001806 to your computer and use it in GitHub Desktop.
A naive string searching algorithm
def search(needle, haystack, end=False):
"""
A naive string searching function.
"""
n = len(needle)
h = len(haystack)
start = 0
offset = n
while offset < h:
if needle == haystack[start:offset]:
if end:
return offset - 1
else:
return start
else:
start += 1
offset += 1
return -1
search('cde', 'abcdabcdefg') # 6
search('cde', 'abcdabcdefg', True) # 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment