all possible combinations

Peter Hansen peter at engcorp.com
Fri Jul 15 01:52:56 CEST 2005


Bengt Richter wrote:
> On Thu, 14 Jul 2005 17:10:37 -0400, William Park <opengeometry at yahoo.ca> wrote:
> It's a one liner in Python too ;-)
> 
>  >>> print ' '.join([x+y+z+q for s in ['abc'] for x in s for y in s for z in s for q in s])

Or for the cost of an import and a lambda, you can keep it looking real 
obscure and generalize it to any size of sequence ('abcdef' or whatever) 
and a result length of up to 52 elements:

 >>> from string import letters as L
 >>> cartesian = lambda seq, num: eval("list(%s for __ in [seq]
%s)" % ('+'.join(L[:num]), 'for %s in __ ' * num % tuple(L[:num])))
# (there are spaces at any line breaks above)

 >>> cartesian('abcde', 6)
['aaaaaa', 'aaaaab', 'aaaaac', 'aaaaad', 'aaaaae', 'aaaaba',
...
'eeeeec', 'eeeeed', 'eeeeee']
 >>> len(_)
15625

<grin>

-Peter



More information about the Python-list mailing list