Skip to content

Instantly share code, notes, and snippets.

@jcbsv
Last active August 29, 2015 14:16
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 jcbsv/f92b9e68c1d5f426b7d8 to your computer and use it in GitHub Desktop.
Save jcbsv/f92b9e68c1d5f426b7d8 to your computer and use it in GitHub Desktop.
Finding a pattern in a list
"""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