1

How can I achieve rolling/sliding window using iter and next without using slice, itertools, len() etc? This is what I have so far, but obviously this does not work, because of append(next(iterator)). And I cannot find any good solution to this.

def windows(iterable,n, m):
     while True:
            try:
                empty_list = []
                append = empty_list.append
                for i in range(s, e):
                    append(next(iterator))
                yield empty_list
                s += m
                e += m
                check += 1
        except StopIteration:
            return

I found this code that does exactly what I want, but it doesn't work with my parameters. Since my iterable parameter uses method called disguise, which is this:

def disguise(iterable):
    for x in iterable:
        yield x

I can just iterate values into a list, but not allowed to do, also parts like "for i in range(-1, -j-1, -1)" confused me a lot with whats going on. Rolling or sliding window iterator?

def window(seq, size, step=1):
    # initialize iterators
    iters = [iter(seq) for i in range(size)]
    # stagger iterators (without yielding)
    [next(iters[i]) for j in range(size) for i in range(-1, -j-1, -1)]
    while(True):
        yield [next(i) for i in iters]
        # next line does nothing for step = 1 (skips iterations for step > 1)
        [next(i) for i in iters for j in range(step-1)]

Is there any simpler approach to this problem?

Desired result will be:

[['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h', 'i'], ['i', 'j', 'k']]

from method call like this:

win(disguise('abcdefghijk'),3,2)
Nick W
  • 59
  • 5

1 Answers1

0

I think this does what you want:

def windows(iterable, n, m):
    it = iter(iterable)
    cur = []
    while True:
        try:
            while len(cur) < n:
                cur.append(next(it))
            yield tuple(cur)
            for _ in range(m):
                if cur:
                    cur.pop(0)
                else:
                    next(it)
        except StopIteration:
            return

print(list(windows(range(10), 3, 2)))
# [(0, 1, 2), (2, 3, 4), (4, 5, 6), (6, 7, 8)]

print(list(windows(range(10), 2, 3)))
# [(0, 1), (3, 4), (6, 7)]
jdehesa
  • 58,456
  • 7
  • 77
  • 121