SoFunction
Updated on 2024-11-17

python solving the hanno tower game

In this article, the example shares the specific code for python to solve the Hannukah Tower game for your reference, the details are as follows

I. Definition of the problem

Baidu Encyclopedia Definition: The Hanoi Tower (also known as the Tower of Hanoi) problem is a puzzle toy originating from an ancient Indian legend. It is said that when the Great Brahma created the world he made three diamond pillars, and on one pillar 64 golden disks were stacked in order from smallest to largest from bottom to top. Brahma ordered Brahmins to use one of the pillars to rearrange the 64 gold disks on the third pillar. It was also stipulated that the gold disks which could not be enlarged on the smaller gold disks could be moved only one disk at a time between the three pillars.

For example, if there are only 3 pieces of the golden disk, then in order to fulfill the rules of the game, then the 8 steps must be completed as shown below:

II. Code Implementation

# Move n plates from column x to column z with the help of column y
def hanoi(n, x, y, z):

 count = 0
 if n == 1: # Recursive exit
  print(x, ' --> ', z)
  return 1
 else:
  # Move the first n - 1 plates from the x-column to the y-column with the help of the z-columns
  count += hanoi(n - 1, x, z, y) # Recursive calls

  # Move the bottom 1 plate from the x-column to the z-column
  count += hanoi(1, x, y, z)

  # Move n - 1 plates from column y to column z with the help of column x.
  count += hanoi(n - 1, y, x, z) # Recursive calls

  return count


def main():

 hanoi_level = input("Please enter the number of Hannukah Tower floors:")
 print("Total number of moves %d" % hanoi(int(hanoi_level), 'X', 'Y', 'Z'))


if __name__ == '__main__':
 main()

The output of the code when the gold disk is 4 layers is:

Please enter the number of floors in the Hannover Tower:4
X --> Y
X --> Z
Y --> Z
X --> Y
Z --> X
Z --> Y
X --> Y
X --> Z
Y --> Z
Y --> X
Z --> X
Y --> Z
X --> Y
X --> Z
Y --> Z
The total number of moves is15

This is the whole content of this article.