I have N
infinite generators. I already know how to take the Cartesian product of these infinite generators because there are several methods listed here ("zig-zag", "expanding square", etc.). I don't really care which method is used as the basis of what I really want: I want to convert an "index into the Cartesian product" into a "tuple of indexes into the original generators" without actually iterating a Cartesian product until that point. I am well aware that I can't actually index into generators. That's fine, because all I need are the indexes themselves. Basically, I want the same thing described here but works for infinite generators.
This will be easiest to understand if we consider a concrete example. Let's consider just two generators (N=2
) and let them both be itertools.count()
so that the indexes into the generators and the values of the generators are all the same.
from itertools import count
a = count() # 0, 1, 2, ...
b = count() # 0, 1, 2, ...
Let's assume I use the zig-zag algorithm because the author so kindly made it available on PyPI.
from infinite import product
p = product(a, b) # (0,0), (0,1), (1,0), (0,2), (1,1), (2,0), ...
I want a function that, given an index into p
, returns a tuple of indexes into a
and b
, like this:
f(2) # (1,0)
f(4) # (1,1)
Again, it doesn't have to be the linear index into the zig-zag algorithm. Any algorithm that produces the Cartesian product on infinite generators can be used as the basis.