Skip to content

Instantly share code, notes, and snippets.

@lad1337
Last active March 2, 2018 16:37
Show Gist options
  • Save lad1337/da8e207c4db8d881776cc39f03aa9752 to your computer and use it in GitHub Desktop.
Save lad1337/da8e207c4db8d881776cc39f03aa9752 to your computer and use it in GitHub Desktop.
a sliding window generator in python
def sliding_window(iterable, size, overlap=0):
"""
>>> list(sliding_window([1, 2, 3, 4], size=2))
[(1, 2), (3, 4)]
>>> list(sliding_window([1, 2, 3], size=2, overlap=1))
[(1, 2), (2, 3)]
>>> list(sliding_window([1, 2, 3, 4, 5], size=3, overlap=1))
[(1, 2, 3), (3, 4, 5)]
>>> list(sliding_window([1, 2, 3, 4], size=3, overlap=1))
[(1, 2, 3), (3, 4)]
>>> list(sliding_window([1, 2, 3, 4], size=10, overlap=8))
[(1, 2, 3, 4)]
"""
start = 0
end = size
step = size - overlap
if step <= 0:
ValueError("overlap must be smaller then size")
length = len(iterable)
while end < length:
yield tuple(iterable[start:end])
start += step
end += step
yield tuple(iterable[start:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment