D
D
Daniil Igorevich2016-06-06 22:25:49
Python
Daniil Igorevich, 2016-06-06 22:25:49

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")

And this is the result:
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

I am superficially familiar with python, but recursion is also recursion in Africa: the first one 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?
I understood the algorithm: transfer n-1 from the main rod to the temporary one, then transfer the last disk in the main rod to the final one and transfer everything from the temporary to the final one, but I didn’t understand how this function works from the inside.
Bought now the book "Towers of Hanoi" to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Mamaev, 2016-06-10
@virtual_universe

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 question

Ask a Question

731 491 924 answers to any question