I am writing python code to print all permutation of a number. Below is my code:
a=[1,2,3,4]
for i in range(len(a)):
temp=a[:]
temp[0],temp[i]=temp[i],temp[0]
def p(temp,i):
k=i+1
if k ==len(a)-1:
print(temp)
return
temp[k],temp[k+1]=temp[k+1],temp[k]
p(temp,k)
temp[k],temp[k+1]=temp[k+1],temp[k]
p(temp,k)
p(temp,i=0)
The idea is to replace every integer at first place and permutate remaining. That's what this for loop is doing:
for i in range(len(a)):
temp=a[:]
temp[0],temp[i]=temp[i],temp[0]
But,for every permutation starting with i,it only prints 4 permutations. for ex: Starting with 1,the permutations should be:
[1,2,3,4]
[1,2,4,3]
[1,3,2,4]
[1,3,4,2]
[1,4,3,2]
[1,4,2,3]
But,its only printing
[1,2,3,4]
[1,2,4,3]
[1,3,2,4]
[1,3,4,2]
4 at second place is not getting printed. Missing:
[1,4,3,2]
[1,4,2,3]
Can anyone tell me what am I doing wrong?