Skip to content

Instantly share code, notes, and snippets.

@rmartinjak
Last active October 4, 2017 19:20
Show Gist options
  • Save rmartinjak/7780289 to your computer and use it in GitHub Desktop.
Save rmartinjak/7780289 to your computer and use it in GitHub Desktop.
sliding window generator, should work in python>=2.6
from itertools import chain, repeat, islice
from collections import deque
def sliding_window(iterable, n, fill=False, fillvalue=None):
it = iter(iterable)
if fill:
it = chain(it, repeat(fillvalue, n - 1))
w = deque(islice(it, n - 1))
for x in it:
w.append(x)
yield w
w.popleft()
for x in sliding_window("abcdefghijkl", 4):
print ''.join(x)
""" outputs:
abcd
bcde
cdef
defg
efgh
fghi
ghij
hijk
"""
for x in sliding_window("abcdefghijk", 4, fill=True, fillvalue='!'):
print ''.join(x)
""" outputs:
abcd
bcde
cdef
defg
efgh
fghi
ghij
hijk
ijk!
jk!!
k!!!
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment