Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active July 21, 2019 05:51
Show Gist options
  • Save estysdesu/af7301fa17817c0d0ac7b5f8952c9bfe to your computer and use it in GitHub Desktop.
Save estysdesu/af7301fa17817c0d0ac7b5f8952c9bfe to your computer and use it in GitHub Desktop.
[Python: windows of an iterable with repeating edge case condition] #window #python
#!/usr/bin/env python3
def window(data, w_size):
""" Get all windows for a list with an odd window size. """
if not getattr(data, '__iter__', False):
raise ValueError("data must be an iterable")
if w_size%2 != 1:
raise ValueError("window size must be odd")
if w_size > len(data):
raise ValueError("window size must be less than the data size")
w_half_size = w_size//2
windows = []
for i, _ in enumerate(data):
if i < w_half_size:
win = data[0:w_size]
windows.append(win)
continue
if i > len(data)-1-w_half_size:
win = data[-w_size:]
windows.append(win)
continue
win = data[i-w_half_size:i+w_half_size+1]
windows.append(win)
return windows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment