Generators for Engineers

A gentle introduction to infinite sequences.

Comments are moderated. It may take a few minutes before your comment appears.
Markdown is supported in your comments.

def moving(iterator, length, step=1):
    ms = tee(iterator, length)
    return izip(*[islice(m,i,None,step) for m,i in zip(ms, count())])

>>> for i in moving(xrange(10), 3):
...    print i
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)
(6, 7, 8)
(7, 8, 9)

# step makes it very flexible
>>> for i in moving(xrange(9), 3, 3):
...     print i
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
Name:
Mail: (not shown)

Please type this: