All permutations of a list

Rainer Deyke root at rainerdeyke.com
Mon Oct 23 01:41:50 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...
> > 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:])]

No. If 'list' is '[]', '[list]' evalutes to '[[]]'.   'not [[]]' evalutes to
0, effectively removing all special handling for the empty list.

If the list of permutations of the empty list was redefined as the empty
list, the following would work:

def perms(list):
  return list and [[list[i]] + p for i in range(len(list))\
    for p in (perms(list[:i] + list[i+1:]) or [[]])]

If you're really desparate, you can save an additional line by using lambda:

perms = lambda list: list and [[list[i]] + p for i in\
  range(len(list)) for p in (perms(list[:i] + list[i+1:]) or [[]])]


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list