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,