need help on generator...

Peter Otten __peter__ at web.de
Fri Jan 21 16:36:28 CET 2005


Joh wrote:

> i'm trying to understand how i could build following consecutive sets
> from a root one using generator :
> 
> l = [1,2,3,4]
> 
> would like to produce :
> 
> [1,2], [2,3], [3,4], [1,2,3], [2,3,4]
> 
> but unfortunately can not, i guess i can do it by using sub generator
> and maybe enumerate, please if you help could you explain a bit the
> trick ? looks like this sub generator thing mess me up.

Here is an (untested) variant that accepts any iterable while trying to
remain memory-efficient. This makes it necessary to shuffle the order of
the output a bit.

from itertools import tee, islice

def gen(iterable, start, end):
    it = iter(iterable)
    while True:
        it, a = tee(it)
        a = tuple(islice(a, end-1))
        for sz in xrange(start, len(a)+1):
            yield a[:sz]
        it.next()

        
if __name__ == "__main__":
    print list(gen(range(1, 5), 2, 4))

# prints:
# [(1, 2), (1, 2, 3), (2, 3), (2, 3, 4), (3, 4)]

Peter




More information about the Python-list mailing list