Some thougts on cartesian products

Christoph Zwerschke cito at online.de
Sun Jan 22 18:19:54 CET 2006


Kay Schluehr schrieb:
> But why isn't this interpreted as [0, 1, 4] like it is in Mathematica?

Because we are thinking of a cartesian product. If you have lists of 
numbers, then there are mane more ways to define a product: tensor 
product, vector product, scalar product, componentwise product...

The cartesian product is a much more generic concept, you can have it 
already for sets:

class sset(set):

     def __mul__(self, other):
         return sset((a,b) for a in self for b in other)

     def __pow__(self, other):
         if isinstance(other, int) and other > 0:
             if other == 1:
                 return self
             elif other == 2:
                 return self*self
             else:
                 return sset(a + (b,) \
                     for a in self**(other-1) for b in self)

Example:

for x in sorted(sset("ACGU")**3):
     print ''.join(x)

AAA
AAC
AAG
AAU
ACA
ACC
.
.
.
UGU
UUA
UUC
UUG
UUU

Now as I'm thinking about it, wouldn't it be nice to have the cartesian 
products on Python sets? Maybe also a method that returns the power set 
of a set (the set of all subsets), or the set of all subsets with a 
given length. You could get a 6/49 lotto tip with something like:

choice(set(range(49)).powerset(6))

-- Christoph



More information about the Python-list mailing list