1

Let say I have list [1, 2, 3, 4, 5, 6, 7] I need produce output like (moving window):

0  1
8  2
16 3
24 4
32 5

0  2
8  3
16 4
24 5
32 6

0  3
8  4
16 5
24 6
32 7

0  1
8  2
16 3
24 4
32 5

when 5-row-height window get to last element of list (7 here) we need start 1, and I need first column be generated like i * 8.

I came with something like this (but not quite):

def w(l):
    global lines
    for i in range(lines - 1, lines + 4):
        location = (i % 5) * 8
        print(f'{location} {l[i]}')
        if lines >= len(l) - 4:
            lines = 1


if __name__ == '__main__':
    ll = [1, 2, 3, 4, 5, 6, 7]
    for i in range(1, 4):
        lines = i
        print(f'-- {i} --')
        w(ll)

Output is:

-- 1 --
0 1
8 2
16 3
24 4
32 5
-- 2 --
8 2
16 3
24 4
32 5
0 6
-- 3 --
16 3
24 4
32 5
0 6
8 7

Maybe deque is an answer?

martineau
  • 119,623
  • 25
  • 170
  • 301
emcek
  • 459
  • 1
  • 6
  • 17
  • 1
    A `deque` would be a good way to implement one, see this [answer](https://stackoverflow.com/a/6822761/355230). – martineau Jun 16 '22 at 21:19

2 Answers2

2

To fix the location part, you can just add enumerate and multiply with 8.

def w(l):
    global lines
    for p,i in enumerate(range(lines - 1, lines + 4)):
        location = p * 8
...

Ritwick Jha
  • 340
  • 2
  • 10
  • Nice (forgot about `enumerate`), however I got problem when `list` is shorter then window. – emcek Jun 17 '22 at 11:01
  • There are a few holes in the logic right now, especially because it is more complicated than need be. It would be easier to rotate the list and take the first n elements rather than calculating the index each time. You could just put conditions on how much to rotate the list by so it's appropriate. Also it's very easy to rotate a list, just by using slices – Ritwick Jha Jun 17 '22 at 14:05
1

You can use sliding_window_view() from numpy:

import numpy as np
sliding_window = np.lib.stride_tricks.sliding_window_view([1, 2, 3, 4, 5, 6, 7], 5)
for i in sliding_window:
    for j, k in enumerate(i):
        print(j*8, k)

Output:

0 1
8 2
16 3
24 4
32 5
0 2
8 3
16 4
24 5
32 6
0 3
8 4
16 5
24 6
32 7
Nin17
  • 2,821
  • 2
  • 4
  • 14