problem with permutations

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cnb

    problem with permutations

    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]]))
  • James Mills

    #2
    Re: problem with permutations

    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@y ahoo.sewrote:
    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]]))
    --

    >


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

    Comment

    • Paul Rubin

      #3
      Re: problem with permutations

      cnb <circularfunc@y ahoo.sewrites:
      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.

      Comment

      Working...