All permutations of a list

June Kim junaftnoon at nospamplzyahoo.com
Mon Oct 23 00:38:01 EDT 2000


"Emile van Sebille" <emile at fenx.com> wrote in message
news:8t08bb$lnvu5$1 at ID-11957.news.cis.dfn.de...
> "Rainer Deyke" <root at rainerdeyke.com> wrote in message
> news:9nNI5.110763$g6.50159527 at news2.rdc2.tx.home.com...
>
> <snip>
>
>
> > 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:])]
> >
>
> ... which permutes into...
>
> def perms3(list):
>   return not [list] or [[list[i]] + p for i in
> range(len(list))\
>     for p in perms(list[:i] + list[i+1:])]

I guess this is a typo, which should've been a recursive
function call to "perms3" itself, instead of calling another
function perms.

However, after the modification, the code doesn't work
because "not [[]]" isn't true.

In addition to that, if someone calls the original perms function
somewhat wrongly, with a tuple argument instead of a list,
it won't give the expected result as well.

So the somewhat protective code should be:

def perms(list):
  if len(list) == 0:
    return [[]]
  return [[list[i]] + p for i in range(len(list))\
    for p in perms(list[:i] + list[i+1:])]

>>> perms((1,2,3))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

>>>perms([1,2,3])
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]


Any comments?


Best Regards,
June





More information about the Python-list mailing list