Reputation: 671
I understand the thinking of how to solve Hanoi with Python recursion, but I don’t understand how we could write this Python language:
def hanoi(n,x,y,z):
if n == 1:
print(x, ' --> ',z)
else:
hanoi(n-1,x,z,y)
print(x, ' --> ',z)
hanoi(n-1,y,x,z)
hanoi(2,'SRC','TMP','TAG')
if the first step is to put (x-1) dishes from source to tmp, why we write hanoi(n-1,z,y) ? why we switch z and y?
thanks!
Upvotes: 1
Views: 2165
Reputation: 635
You are understanding the variables wrong:
n
is the number of disksx
is the first poley
is the pole used for transferringz
is the pole for the destination of the transferred diskSince we want to solve hanoi(n, x, y, z)
, we do as follows:
n==1
bit)x
) to the final pole (z
) using the temporary pole (y
)We do this by moving n-1
disks from x
to y
using z
(aka hanoi(n-1, x, z, y)
), then moving the last disk to z
, then moving all remaining disks (which are on y
) onto z
(the final pole) with hanoi(n-1, y, x, z)
Here's a gif to illustrate:
Upvotes: 4