The problem was to write the python code to generate all the permutations of the numbers {1,2,3,...,n}. So, I write this code:
def permute(n):
if n==len(a):
print a
return
for i in range(n,len(a)):
swap(i,n)
permute(n+1)
swap(i,n)
def swap(x,y):
a[x],a[y]=a[y],a[x]
a=[1,2,3,4] #any list
permute(0)
And it worked perfectly. But then thanks to the free time that I did have, I modified it a bit and wrote this code:
def permute(n):
if n==len(a):
print a
return
for i in range(n,len(a)):
swap(a[i],a[n]) #modification
permute(n+1)
swap(a[i],a[n]) #modification
def swap(x,y):
x,y=y,x #modification
a=[1,2,3,4]
permute(0)
This time it didn't work. But after then, I read a bit about how the assigning of variables to values is different in python.
But still I would like to know what, according to you, is wrong with the second code, so that I can cross-check and discuss what I think is going wrong! That's my first question.
My second question is how the swapping of values takes place in a python list? Is it something different from what will happen with simple values? Because both the codes above seem to apply so. But I cannot figure out it a way I can make myself understand, plus it further confused me that then how python manipulates its lists.
I am sure there is something in the design of Python language that I don't know about leading to all these confusions. Help me sort them out and if possible, use somewhat picture visualizations. It would be very easy then for me to understand what's going on!!
This is the reason:
def swap(x,y):
x, y = y, x
This just swaps the local names. x
will then equal y
, and vice versa, but only inside that function. Outside that function (global scope), nothing will change.
Assuming:
x = a[i]
y = a[n]
To swap values in a list, you must set them:
a[n] = x
a[i] = y
Which is that same as:
a[i], a[n] = y, x
And since y = a[n]
and x = a[i]
, it is the same as:
a[i], a[n] = a[n], a[i]
The swap
function is swapping the local variables x
and y
and not the global array.
def swap(x,y):
x,y=y,x
This is completely wrong
You can instead do the following
Change the function body to
return y,x
and call the function as a[n],a[i] = swap(a[i],a[n])
Or directly swap in-place a[n],a[i] = a[i],a[n]
If the list is composed only by numbers:
A[i] = A[i] + A[n]
A[n] = A[i] - A[n]
A[i] = A[i] - A[n]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.