all possible combinations

rbt rbt at athop1.ath.vt.edu
Fri Jul 15 10:00:21 EDT 2005


Wow. That's neat. I'm going to use it. Thanks!

On Thu, 2005-07-14 at 19:52 -0400, Peter Hansen wrote:
> 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