Skip to content

Instantly share code, notes, and snippets.

@anossov
Created December 6, 2015 17:11
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 anossov/650e1e83c8c964b52e38 to your computer and use it in GitHub Desktop.
Save anossov/650e1e83c8c964b52e38 to your computer and use it in GitHub Desktop.
Python implementation of exact-matching Bitap
def bitap_search(text, pattern):
"""
Returns position of pattern in text or -1 if it wasn't found.
text and pattern are strings.
>>> bitap_search("test text", "tex")
5
>>> bitap_search("test text", "z")
-1
"""
m = len(pattern)
if m == 0:
return 0
R = [False] * (m + 1)
R[0] = True
i = 0
while i < len(text):
k = m
while k >= 1:
R[k] = R[k - 1] and (text[i] == pattern[k-1])
k -= 1
# R[m] is the last element in R. If it's True, that means the entire pattern matched and we can return its position in the text.
if R[m]:
# i is now at the end of the pattern. Subtracting (m-1) puts us at the start of the pattern in text.
return i - m + 1
i += 1
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment