[Numpy-discussion] how do I list all combinations

Alan G Isaac aisaac@american....
Sun Dec 30 12:25:07 CST 2007


On Wed, 26 Dec 2007, Mathew Yeates apparently wrote: 
> r1=["dog","cat"] 
> r2=[1,2] 
> I want to return [["dog",1],["dog",2],["cat",1],["cat",2]] 


This is a Cartesian product.

Sage has ``cartesian_product_iterator`` for this.
Also 
<URL:http://www.sagemath.org/doc/html/ref/module-sage.combinat.cartesian-product.html>

Here is a Cookbook implementation.
<URL:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478>
The generator may be adequate to your needs.

Here is a recursive implementation that does not use 
multi-dimensional indexing:

def set_product(*sets):
    last_set = sets[-1]
    drop_last = sets[:-1]
    if drop_last:
        result = set( x+(y,)
                      for x in set_product(*drop_last)
                      for y in last_set )
    else:
        result = set( (y,) for y in last_set )
    return result

Sorry for a late reply.  I'm catching up on email...

Cheers,
Alan Isaac





More information about the Numpy-discussion mailing list