Skip to content

Instantly share code, notes, and snippets.

@himaprasoonpt
Created February 9, 2019 13:50
Show Gist options
  • Save himaprasoonpt/78873fb9dedcf686df636876a41a1be6 to your computer and use it in GitHub Desktop.
Save himaprasoonpt/78873fb9dedcf686df636876a41a1be6 to your computer and use it in GitHub Desktop.
Returns a sliding window (of width n) over data from the iterable
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