0

I want to write a recursive function p() that takes a list and returns a list of all permutations of the input list.

Ex.

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

I want to recursively call on a sublist l[1:] for all permutations of all elements of the original input list except the first element, l[0], and then generate the permutations of the original list by adding l[0] to those permutations.

So far, I have

def p(list):
    if len(list)==1 or 0:
        return list
    result = []
    for i in list[1:]:
        result.append(i + list[0])
    result += [list]
    return result

But I know something is wrong.... help please?

Dan Oberlam
  • 2,435
  • 9
  • 36
  • 54
user3638865
  • 119
  • 1
  • 2
  • 8
  • 2
    Are you just writing this as an exercise? If not, you could just use [`itertools.permutations`](https://docs.python.org/2/library/itertools.html#itertools.permutations). – BrenBarn Jun 01 '14 at 04:55

1 Answers1

0

I don't know that is what you want but check it out

from itertools import permutations

l = [1, 2, 3, 4, 5]
new_l = list(permutations(l, len(l)))

it will output something like

[(1, 2, 3, 4, 5),
 (1, 2, 3, 5, 4),
 (1, 2, 4, 3, 5),
 (1, 2, 4, 5, 3),
 (1, 2, 5, 3, 4),
 ...

Hope this helps!