this function takes an arbitrary number of lists as input and returns the Cartesian product.
ex:
>>> cp((1,2),(3,4,5),(6,))
[[1, 3, 6], [1, 4, 6], [1, 5, 6], [2, 3, 6], [2, 4, 6], [2, 5, 6]]
technically a Cartesian product is a set of sets, not a sequence of sequences, so you'll have to use set() on both levels if you want that behavior.
note that this function can easily be used to combine any number of nested for loops into one, ex. for x, y, z in cp(*[range(10)]*3): print x, y, z
def cp(*lists): o = [[]] for ell in reversed(lists): o = [[el] + el2 for el in ell for el2 in o] return o
also note that this program returns [[]] for cp() and [] for cp([]). that's probably the reverse of how it should work.
Re: Cartesian Product
ikiel | 09/01/2010, 23:08
not posting any more entries until they fix that code python problem.