-6

Suppose I have the following list:

>>> my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to write a function that will iterate over slices of n elements to the left and right of each item of this list:

def sliding_window_n_elements_left_and_right(lst, n):
    ...

The function should work like this:

>>> list(sliding_window_n_elements_left_and_right(my_list, 0))
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]

>>> list(sliding_window_n_elements_left_and_right(my_list, 1))
[[0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10]]

>>> list(sliding_window_n_elements_left_and_right(my_list, 2))
[[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10]]

Thank you for your time and skill!

  • Possible duplicate of https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator-in-python – MohitC Oct 17 '17 at 14:02
  • 1
    Well it seems you have posted a function specification and asked someone to write the function for you. This doesn't seem to be the normal type of question. I just wanted you to review [ask] and decide for yourself. – wwii Oct 17 '17 at 15:19

1 Answers1

2

You can slice the list at each index i padding with n on left and right to create a fixed window of max size 2n+1:

def sliding_window_n_elements_left_and_right(lst, n):
    # start = max(0, i-n) prevents slice from starting at negative value
    return [lst[max(0, i-n):i+n+1] for i in range(len(lst))]

print(sliding_window_n_elements_left_and_right(my_list, 0))
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]

print(sliding_window_n_elements_left_and_right(my_list, 1))
# [[0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10]]

print(sliding_window_n_elements_left_and_right(my_list, 2))
# [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10]]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139