Last active
October 4, 2017 19:20
-
-
Save rmartinjak/7780289 to your computer and use it in GitHub Desktop.
sliding window generator, should work in python>=2.6
This file contains hidden or 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 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