Created
June 1, 2011 04:53
-
-
Save twaddington/1001806 to your computer and use it in GitHub Desktop.
A naive string searching algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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