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 ????
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With