Given a natural number n. We try to generate all permutations from 1 to n in Python without any prebuild method. I used recursion as follows to achieve our desired goal in python
# Generate all permutations in Python with recursion
n = int(input('Enter a number: '))
permutationLst = []
validlst = [0] * (n + 1)
def generate():
if len(permutationLst) >= n:
print(permutationLst)
return None
for i in range(1, n + 1):
if validlst[i]:
continue
validlst[i] = 1
permutationLst.insert(i, i)
generate()
permutationLst.pop()
validlst[i] = 0
generate()
But the output of above code is for n=3 is:
Enter a number: 3
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 1, 3]
[3, 1, 2]
[3, 1, 2]
How can I resolve this problem that some permutations are not generated and duplicates are generated? Note that I'm a beginner in Python.
I try to analyze the recursion tree of my code but I can't figure out the problem.