Skip to content

Instantly share code, notes, and snippets.

@espdev
Last active October 26, 2017 10:33
Show Gist options
  • Save espdev/d0e40d8b9ed007bc49ab57b3297f4c65 to your computer and use it in GitHub Desktop.
Save espdev/d0e40d8b9ed007bc49ab57b3297f4c65 to your computer and use it in GitHub Desktop.
Sliding window over data from the sequence
import itertools
def slide(seq, n=2):
"""Returns a sliding window (of width n) over data from the sequence
s -> (s0, s1, ..., s[n-1]), (s1, s2, ..., sn), ...
"""
it = iter(seq)
result = tuple(itertools.islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment