Ask Your Question

Revision history [back]

The fastest is

sage: from itertools import product
sage: for p in product((1,-1), repeat=4): print p
(1, 1, 1, 1)
(1, 1, 1, -1)
...
(-1, -1, -1, -1)

You can evaluate the timings

sage: timeit('for p in Words(length=8, alphabet=[-1,1]): pass')
25 loops, best of 3: 7.77 ms per loop
sage: timeit('for p in cartesian_product_iterator([[-1,1] for i in range(8)]): pass')
625 loops, best of 3: 868 µs per loop
sage: timeit('for p in product((1,-1), repeat=8): pass')
625 loops, best of 3: 26.6 µs per loop

So product is fastest, then comes cartesian_product_iterator and then words. The difference is non non-negligible and if your length is large you may prefer use the version with product.

The fastest is

sage: from itertools import product
sage: for p in product((1,-1), repeat=4): print p
(1, 1, 1, 1)
(1, 1, 1, -1)
...
(-1, -1, -1, -1)

You and if you want the list

sage: list(product((1,-1), repeat=4))
[(1, 1, 1, 1), (1, 1, 1, -1), ..., (-1, -1, -1, -1)]

If you care about performances, you can evaluate the timings

sage: timeit('for p in Words(length=8, alphabet=[-1,1]): pass')
25 loops, best of 3: 7.77 ms per loop
sage: timeit('for p in cartesian_product_iterator([[-1,1] for i in range(8)]): pass')
625 loops, best of 3: 868 µs per loop
sage: timeit('for p in product((1,-1), repeat=8): pass')
625 loops, best of 3: 26.6 µs per loop

So product is fastest, then comes cartesian_product_iterator and then words. The difference is non non-negligible and if your length is large you may prefer use the version with product.non-negligible!