Some thougts on cartesian products
Bryan Olson
fakeaddress at nowhere.org
Sun Jan 22 20:25:36 EST 2006
Christoph Zwerschke wrote:
> In Python, it is possible to multiply a string with a number:
>
> >>> "hello"*3
> 'hellohellohello'
Which is really useful.
> However, you can't multiply a string with another string:
>
> >>> 'hello'*'world'
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> TypeError: can't multiply sequence by non-int
>
> Sometimes I was missing such a feature.
> What I expect as the result is the "cartesian product" of the strings.
There's no such thing; you'd have to define it first. Are duplicates
significant? Order?
What you seem to want is easy enough:
[a + b for a in 'hello' for b in 'world']
[...]
> Cartesian products may be generally interesting for iterables:
And maybe you want the result to be a generator:
(a + b for a in 'hello' for b in 'world')
New language features should be widely useful, and difficult or
awkward to code in Python as it is. All-combinations-of-sequences
is trivial to code and rarely needed.
--
--Bryan
More information about the Python-list
mailing list