problem with permutations

C

cnb

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[0] == elem:
return list(acc + tuple(lista[1:]))
else:
return upd(lista[1:], elem, acc + tuple([lista[0]]))
 
J

James Mills

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

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[0] == elem:
return list(acc + tuple(lista[1:]))
else:
return upd(lista[1:], elem, acc + tuple([lista[0]]))
 
P

Paul Rubin

cnb said:
perms([]) -> [[]];
perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])].

I think the most direct transcription might be:

def perms(xs):
if len(xs)==0: return [[]]
return [([h]+t) for h in xs
for t in perms([y for y in xs if y not in [h]])]

But it is rather inefficient, as is the Erlang version.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,588
Members
45,095
Latest member
EmiliaAlfo

Latest Threads

Top