Cartesian Product

| | Comments (2) | Trackbacks (0) | Next |

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.

 

 

 

 

 

Comments

Re: Cartesian Product

ikiel | 09/01/2010, 23:08

not posting any more entries until they fix that code python problem.

Re: Cartesian Product

ikiel | 26/02/2010, 01:03

i figured out how to solve it. the solution is not to use Chrome. i updated the entry in firefox and it fixed it.

Add comment
 authimage