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)