How do I return a list of list of this code?

Question:

I found this code for printing all the permutations from an input list, i want to return a nested list but have been unable to do so. The list returned is either empty or the nested list of has all the same permutations. I can also do with a little help in understanding the logic.

ref : https://stackoverflow.com/questions/104420/how-do-i-generate-all-permutations-of-a-list.[one of the solutions].
edit 1 : list assignment added.

l = []
def perm(a, k=0):
   if k == len(a):
      print(a)
      l.append(a)
   else:
      for i in range(k, len(a)):
         a[k], a[i] = a[i] ,a[k]
         perm(a, k+1)
         a[k], a[i] = a[i], a[k]

perm([1,2,3])
print(l)

Output for list l : [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

  • I am not allowed to use itertools.

Thanks,

Asked By: boom

||

Answers:

At each recursive step the code is altering the list in place. So what the code below does is make a copy of the list once it reaches the base case, and returns it. Then it collects the return values into an empty list on it’s way back up the recursive call stack and outputs all lists combined.

def perm(a, k=0):
    if k == len(a):
        return [a[:]]
    lst = []
    for i in range(k, len(a)):
        a[k], a[i] = a[i] ,a[k]
        lst += perm(a, k+1)
        a[k], a[i] = a[i], a[k]
    return lst

print(perm([1,2,3]))

Output:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

Here is a slightly improved version

def perm(a, k=[]):
    if not a: return [k]
    lst = []
    for i in range(len(a)):
        lst += perm(a[:i] + a[i+1:], k + [a[i]])
     return lst
print(perm([1,2,3]))
Answered By: Alexander
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.