Answer the question
In order to leave comments, you need to log in
recursion in python?
Now I'm trying to understand the algorithm for solving the Tower of Hanoi problem, here is the solution code:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
print(fromPole, toPole, withPole, height)
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole, height)
print(fromPole, toPole, withPole, height)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp, height):
print("moving disk from",fp,"to",tp)
print("height", height)
moveTower(3,"A","B","C")
A B C 3
A C B 2
A B C 1
moving disk from A to B
height 1
A B C 1
moving disk from A to C
height 2
A C B 2
B C A 1
moving disk from B to C
height 1
B C A 1
moving disk from A to B
height 3
A B C 3
C B A 2
C A B 1
moving disk from C to A
height 1
C A B 1
moving disk from C to B
height 2
C B A 2
A B C 1
moving disk from A to B
height 1
A B C 1
print(fromPole, toPole, withPole, height)
, which is on line 3, displays everything clearly. After firing moveTower(height-1,fromPole,withPole,toPole)
fromPole = A, withPole = C, toPole = B? And why is it print(fromPole, toPole, withPole, height)
displayed for the third time A B C 1
? Why do these values change? Answer the question
In order to leave comments, you need to log in
For the future:
Download thonny - a very handy IDE for such tasks. Of course, writing web applications in it is not very good, but looking to understand the solution to the problem is the very thing.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question