Created
February 9, 2019 13:50
-
-
Save himaprasoonpt/78873fb9dedcf686df636876a41a1be6 to your computer and use it in GitHub Desktop.
Returns a sliding window (of width n) over data from the iterable
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
from itertools import islice | |
def sliding_window(seq, n=3): | |
""" | |
Returns a sliding window (of width n) over data from the iterable | |
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... | |
""" | |
it = iter(seq) | |
result = tuple(islice(it, n)) | |
if len(result) <= n: | |
yield result | |
for elem in it: | |
result = result[1:] + (elem,) | |
yield result | |
for i in sliding_window(range(10),3): | |
print(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment