Some thougts on cartesian products

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jan 22 13:03:20 EST 2006


On Sun, 22 Jan 2006 18:29:45 +0100, Christoph Zwerschke wrote:

> Alex Martelli wrote:
>> Kay Schluehr <kay.schluehr at gmx.net> wrote:
>>> range(3)**2
>>> But why isn't this interpreted as [0, 1, 4] like it is in Mathematica?
>> 
>> Since range(3)*2 is [0, 1, 2, 0, 1, 2], it would be horribly, painfully
>> inconsistent if **2 was interpreted as "square each item".
> 
> Yes. Python does not interpreate the product of a list with a number as 
> a scalar product. Otherwise range(3)*2 should be [0, 1, 4] as well.
> 
> For doing such things I would use a vector subtype of list.

Not everything needs to be a separate class! Why create a magic class for
every piece of functionality you want? Just create functions that operate
on existing classes!

Instead of a class that supports cartesian products, make a function that
takes two sequences and returns the cartesian product of them. (This will
likely be best implemented as a generator.) If you write it properly,
which is to say if you don't go out of your way to break it, this function
will *automatically* work on any sequence type, lists, tuples, strings,
and things you and I haven't even thought of.

What advantage is there to creating a "list with cartesian product"
subclass of list?



-- 
Steven.




More information about the Python-list mailing list