itertools product(infinite iterator) hangs
ast
none at gmail.com
Sat Sep 14 02:18:07 EDT 2019
Le 14/09/2019 à 04:26, Oscar Benjamin a écrit :
> I've been staring at this for a little while:
>
> from itertools import product
>
> class Naturals:
> def __iter__(self):
> i = 1
> while True:
> yield i
> i += 1
>
> N = Naturals()
> print(iter(N))
> print(product(N)) # <--- hangs
>
> When I run the above the call to product hangs but I can't see why. I
> would expect that since I'm not iterating over the product it would
> just call iter(N) but clearly not since iter(N) returns a generator
> instantly where as product(N) hangs.
>
> What am I missing?
>
> Oscar
>
here is a pseudo code for product:
def product(*args, repeat=1):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
clearly "tuple(pool)" hangs with an infinite iterable pool
More information about the Python-list
mailing list