Skip to content

Instantly share code, notes, and snippets.

@nrvale0
Last active January 30, 2017 23:33
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 nrvale0/7bd1d0c66dd122824622487d6d4cc400 to your computer and use it in GitHub Desktop.
Save nrvale0/7bd1d0c66dd122824622487d6d4cc400 to your computer and use it in GitHub Desktop.
Python string matching
#!/usr/bin/env python3
S = '01000101010110011101010101'
N = len(S)
posS = 0
A = '101'
k = len(A)
posA = 0
def strinspect(source, pattern):
if len(pattern) > len(source):
return False
i = 0
while i < len(pattern):
if pattern[i] is source[0 + i]:
i += 1
else:
return False
return True
print("Source is '{}'...".format(S))
print("Search is '{}'...".format(A))
print("")
hits = 0
while posS < N:
if strinspect(S[posS:], A):
hits += 1
print("Found a hit for {} at head of {}...".format(A, S[posS:]))
posS +=1
print("\nTotal hits: {}".format(hits))
~ /tmp/foo.py 
Source is '01000101010110011101010101'...
Search is '101'...

Found a hit for 101 at head of 101010110011101010101...
Found a hit for 101 at head of 1010110011101010101...
Found a hit for 101 at head of 10110011101010101...
Found a hit for 101 at head of 101010101...
Found a hit for 101 at head of 1010101...
Found a hit for 101 at head of 10101...
Found a hit for 101 at head of 101...

Total hits: 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment