Ask Your Question

Revision history [back]

I am not sure i understand your question. If you want, for a given (n,k), get all the possible tuples (a_1, ..., a_n) where 1 <= a_i <= k for all i you can use Multidimensional enumeration:

sage: car = lambda n,k : cartesian_product_iterator([xrange(1,k+1) for i in range(n)])
sage: list(car(4,2))
[(1, 1, 1, 1),
 (1, 1, 1, 2),
 (1, 1, 2, 1),
 (1, 1, 2, 2),
 (1, 2, 1, 1),
 (1, 2, 1, 2),
 (1, 2, 2, 1),
 (1, 2, 2, 2),
 (2, 1, 1, 1),
 (2, 1, 1, 2),
 (2, 1, 2, 1),
 (2, 1, 2, 2),
 (2, 2, 1, 1),
 (2, 2, 1, 2),
 (2, 2, 2, 1),
 (2, 2, 2, 2)]

I am not sure i understand your question. If you want, for a given (n,k), get all the possible tuples (a_1, ..., a_n) where 1 <= a_i <= k for all i you can use Multidimensional enumeration:

sage: car = lambda n,k : cartesian_product_iterator([xrange(1,k+1) for i in range(n)])
sage: list(car(4,2))
[(1, 1, 1, 1),
 (1, 1, 1, 2),
 (1, 1, 2, 1),
 (1, 1, 2, 2),
 (1, 2, 1, 1),
 (1, 2, 1, 2),
 (1, 2, 2, 1),
 (1, 2, 2, 2),
 (2, 1, 1, 1),
 (2, 1, 1, 2),
 (2, 1, 2, 1),
 (2, 1, 2, 2),
 (2, 2, 1, 1),
 (2, 2, 1, 2),
 (2, 2, 2, 1),
 (2, 2, 2, 2)]

Note that i am creating an iterator and not a list, so that, if i do something like

sage: for i in car(1000,1000):
....:     blabla(i)

the tuples are created on the fly and my memory won't get stuck.

I am not sure i understand your question. If you want, for a given (n,k), get all the possible tuples (a_1, ..., a_n) where 1 <= a_i <= k for all i you can use Multidimensional multidimensional enumeration:

sage: car = lambda n,k : cartesian_product_iterator([xrange(1,k+1) for i in range(n)])
sage: list(car(4,2))
[(1, 1, 1, 1),
 (1, 1, 1, 2),
 (1, 1, 2, 1),
 (1, 1, 2, 2),
 (1, 2, 1, 1),
 (1, 2, 1, 2),
 (1, 2, 2, 1),
 (1, 2, 2, 2),
 (2, 1, 1, 1),
 (2, 1, 1, 2),
 (2, 1, 2, 1),
 (2, 1, 2, 2),
 (2, 2, 1, 1),
 (2, 2, 1, 2),
 (2, 2, 2, 1),
 (2, 2, 2, 2)]

Note that i am creating an iterator and not a list, so that, if i do something like

sage: for i in car(1000,1000):
....:     blabla(i)

the tuples are created on the fly and my memory won't get stuck.