I am trying to improve my understanding of the code for the recursive solution to the towers of hanoi in python.
this code:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
print( " "*(3-height), "moveTower:", height, fromPole, toPole )
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole,height)
moveTower(height-1,withPole,toPole,fromPole)
#print(withPole)
def moveDisk(fp,tp,height):
print(" "*(4-height), "moving disk", "~"*(height), "from",fp,"to",tp)
moveTower(3,"A","B","C")
will print the correct moves required to solve the puzzle and so i asked on stack overflow a while ago for an explanation on how it does so. I was given this answer
moveTower: 3 A B
moveTower: 2 A C
moveTower: 1 A B
moving disk ~ from A to B
moving disk ~~ from A to C
moveTower: 1 B C
moving disk ~ from B to C
moving disk ~~~ from A to B
moveTower: 2 C B
moveTower: 1 C A
moving disk ~ from C to A
moving disk ~~ from C to B
moveTower: 1 A B
moving disk ~ from A to B
The only thing I do not understand about this explanation is how within the recursion the disc destination (peg a,b,c) changes? the 3rd line - moveTower: 1 A B, is correct and I know that the disc should be moved from A to B but I don't understand how we went from A to C (the 2nd line) to the new destination being B! This is hard to explain, if you don't understand what I mean please ask but I would really like some help in understanding this!
this is what i understand the code would look like for 3 discs from=A, to=B, with=C and I have written what i think the recursion would look like (this is ignoring most of the code, I'm just focusing on the top part
def moveTower(3,A, B, C):
if height >= 1:
moveTower(2,A,C,B)
moveTower(1,A, C, B) #so this line of code should be A,B,C but why? as in recursion do we not simply repeat the code again and again? so why would it change if the code initially is ACB why does it change to ABC?
moveDisk(A,B,3)
moveTower(1,C,B,A)