# problem with permutations

James Mills prologic at shortcircuit.net.au
Sun Sep 7 23:40:34 CEST 2008

```Hi,

Here's a (better?) function:

def permutate(seq):
if not seq:
return [seq]
else:
temp = []
for k in range(len(seq)):
part = seq[:k] + seq[k+1:]
for m in permutate(part):
temp.append(seq[k:k+1] + m)
return temp

cheers
James

On Mon, Sep 8, 2008 at 6:47 AM, cnb <circularfunc at yahoo.se> wrote:
> I am trying to translate this elegant Erlang-code for finding all the
> permutations of a list.
> I think it is the same function as is but it doesn't work in Python.
> -- is upd in Python. It works as it should.
>
> perms([]) -> [[]];
> perms(L)  -> [[H|T] || H <- L, T <- perms(L--[H])].
>
> def perms(lista):
>    if lista == []:
>        return [[]]
>    else:
>        for h in lista:
>            return [([h]+[t]) for t in perms(upd(lista, h))]
>
> def upd(lista, elem, acc=tuple([])):
>    lista = tuple(lista)
>    if lista == ():
>        return list(acc)
>    if lista == elem:
>        return list(acc + tuple(lista[1:]))
>    else:
>        return upd(lista[1:], elem, acc + tuple([lista]))
> --
> http://mail.python.org/mailman/listinfo/python-list
>

--
--
-- "Problems are solved by method"

```

More information about the Python-list mailing list