With python, you can easily pass the Tower of Hanoi game (recursive function)

[]There are actually rules to follow in the Tower of [Hanoi game. You can use recursive thinking. In fact, it is two tossing back and forth in a group.] If you can figure it out on your own, you might get yourself dizzy.

Let’s solve this problem with recursive thinking. It’s actually very simple. At the beginning, there are n plates on column A. I can put the top n-1 plates on top of B first, and put the bottom one on column C. Then put the n-1 pieces on the B column to the C column.

Here is the code, very simple:

def hnt(n,a,b,c):
    if n == 1:
        print( f' {a} column top --> {c} column' )
     else :
        hnt(n -1 ,a,c,b)
        print( f' {a} column top one --> {c} column' )
        hnt(n -1 ,b,a,c)
hnt( 5 , 'A' , 'B' , 'C' )

Run it and this answer appears:

A column top one --> C column 
A column top one --> B column 
C column top one --> B column 
A top one --> C column 
B top one --> A column The top one of 
B pillar --> C pillar 
The top one of A pillar --> C pillar 
The top one of A pillar --> B pillar 
The top one of C pillar --> B pillar 
The top one of C pillar --> A pillar 
The top one of B pillar --> A pillar 
is the top one of C pillar --> B pillar 
is the top one of A pillar --> C pillar 
is the top one of A pillar --> B pillar 
is the top one of C pillar --> B pillar 
A column top one --> C column 
B top one --> A column 
B top one --> C column 
A top one --> C column 
B top one -->A pillar 
C pillar is the top one --> B pillar
The top one of the C pillar --> the top one of the A pillar 
B --> the top one of the A pillar 
B --> the top one of the C pillar 
A --> the top one of the C pillar 
A --> the B pillar The top one of 
the C column --> the top one of the B column --> 
the top one of the C column 
and the B column --> the top one of the A column 
and the B column --> the top one of the C column 
and the A column --> the C column

In fact, the Tower of Hanoi can also be played with lists, and using pop() is equivalent to popping the top one at a time.

Leave a Comment

Your email address will not be published. Required fields are marked *