Last active
October 26, 2017 10:33
-
-
Save espdev/d0e40d8b9ed007bc49ab57b3297f4c65 to your computer and use it in GitHub Desktop.
Sliding window over data from the sequence
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
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