Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • I am not allowed to use itertools.

Thanks,

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading