Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question for python experts: code doesn't work when called with generators

I have a small snippet that does not work in an inexplicable way.
The purpose is to generate all combinations of two or more sequences.
It works when called with lists, but it doesn't when called with generators.

def comb(seqs):
    if seqs:
        for item in seqs[0]:
            for rest in comb(seqs[1:]):
                yield [item] + rest
    else:
        yield []

if __name__=="__main__":
    x=[1,2]
    y=[3,4]
    print list(comb([x,y])) # prints [[1, 3], [1, 4], [2, 3], [2, 4]]

    def gen1(): yield 1; yield 2
    def gen2(): yield 3; yield 4
    x=gen1()
    y=gen2()
    print list(comb([x,y])) # prints [[1, 3], [1, 4]  WHY ????
like image 520
Alain Avatar asked Mar 20 '26 05:03

Alain


1 Answers

A generator is exhausted once it has generated everything that it is going generate whereas a list can be iterated through multiple times.

Your comb generator relies on being able to iterate through the second and later sequences that it is passed multiple times so won't work if these sequences are actually a generator.

like image 72
CB Bailey Avatar answered Mar 21 '26 20:03

CB Bailey