All permutations of a list

Richard van de Stadt stadt at cs.utwente.nl
Thu Oct 26 17:59:55 EDT 2000


Rainer Deyke wrote:
> 
> "Richard van de Stadt" <stadt at cs.utwente.nl> wrote in message
> news:39F393B5.A978CC9D at cs.utwente.nl...
> > Rainer Deyke wrote:
> > > def ins(a, list):
> > >   return [list[:i] + [a] + list[i:] for i in range(len(list) + 1)]
> >
> > After having seen this, my colleague came up with this two-line solution,
> > a version that doesn't need an ins-part:
> >
> > perms [] = [[]]
> > perms xs = concat [ map (x:) (perms (xs--[x])) | x <- xs ]
> >
> > How would that be in Python? I guess it's about time I start
> > downloading v2.0.
[...]
> 
> Here's my short Pythonic permutation function:
> 
> def perms(list):
>   if list == []:
>     return [[]]
>   return [[list[i]] + p for i in range(len(list))\
>     for p in perms(list[:i] + list[i+1:])]

My collegue found another Miranda/Amanda solution, which looks
similar (or is it _the_ equivalent?)

perms [] = [[]]
perms l  = [ x:p | x <- l ; p <- perms (l--[x]) ]

x <- l: x walks through all values of l
for every x, p is set to all permutations of l_without_x
x:p means x with p appended.

Richard.



More information about the Python-list mailing list