N
N
Natalia Veis2022-01-31 22:12:55
Python
Natalia Veis, 2022-01-31 22:12:55

Towers of Hanoi in Python?

Please help me, I've been sitting all day and I don't understand how the function works.
Here is the code:

def move(n, start, finish) :
    if n==1:
        print(n, start, finish) 
    else:
         tmp= 6 - start - finish
         move(n - 1, start, tmp)
         print(n, start, finish) 
         move(n - 1, tmp, finish)
n=int(input())
move(n, 1, 3)

What is not clear: how the program understands the code and copies the rings , that is, if I write 6 rings, for example, it will copy 5 to the temporary variable tmp .. Where it is indicated in the code how. Is it that the argument assignment method looks like this after else..? And I still don’t understand how the program understands that a larger ring cannot be placed on a smaller one? That is, as he understands, is it not indicated in the code that 2 cannot be put on 1? n-1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Evseev, 2022-01-31
@Nalali98

def hanoi(a, b, c, n):
    if n == 1:  # рекурсивное конечное условие
        print(a, '->', c)
    else:
        hanoi(a, c, b, n - 1)
        print(a, '->', c)
        hanoi(b, a, c, n - 1)

hanoi('A', 'B', 'C', 5)

Here is the code that will describe all the steps. The arguments to the hanoi function are three towers A, B, C and a number.
If the number is one, then it is logical that only one movement step is required. If the number is not equal to 1, then the function calls itself, but decreasing the number by one, since one operation has already occurred and swaps the towers, after which it prints a new result. After that, it checks again whether it is equal to 1, if not, then the cycle repeats.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question