Last active
August 29, 2015 14:16
-
-
Save jcbsv/f92b9e68c1d5f426b7d8 to your computer and use it in GitHub Desktop.
Finding a pattern in a list
This file contains 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
"""Finding a pattern in a list | |
A solution to the Stack Overflow question: | |
http://stackoverflow.com/questions/6656310/finding-patterns-in-a-list | |
""" | |
import itertools | |
def pattern_match(pattern, sequence): | |
"""Count the number of times that pattern occurs in the sequence.""" | |
pattern = tuple(pattern) | |
k = len(pattern) | |
# create k iterators for the sequence | |
i = itertools.tee(sequence, k) | |
# forward the iterators | |
for j in range(k): | |
for _ in range(j): | |
next(i[j]) | |
count = 0 | |
for q in zip(*i): | |
if pattern == q: | |
count += 1 | |
return count | |
def main(): | |
p = [4, 5, 6] | |
l = [1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6] | |
count = pattern_match(p, l) | |
print('Found {} instances of {} in the list.'.format(count, p)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment