×

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we will first learn about the game's rules. Without spending any time, let's begin.

In python, what is the Tower of Hanoi?

Three identical rods and n discs of various sizes are used in this mathematical puzzle game. The discs are arranged in the first rod with the largest disc at the bottom and the smallest disc at the top.The disc must be placed in the final rod via the intermediate rod in the same order in order to complete the puzzle.

Python Program for Tower of Hanoi
Tower of Hanoi game

Rules of Tower of Hanoi in Python:

  • One disc can only be moved at a time.
  • Only the top disc could be moved and positioned on top of any other rod.
  • Only larger discs can be stacked on top of smaller ones.

An example of the game:

Consider that there are initially 3 discs set up as follows.

Python Program for Tower of Hanoi

Move- 0

We'll initially transfer the disc from A to C.

Python Program for Tower of Hanoi

Move: 1

Moving the disc now from A to B

Python Program for Tower of Hanoi

Move: 2

The disc of rod C will then be moved to position B.

Python Program for Tower of Hanoi

Move: 3

Following this, the disc will be transferred from A to C.

Python Program for Tower of Hanoi

Move: 4

Transfer the disc now from B to A.

Python Program for Tower of Hanoi

Move: 5

The disc of rod B must then be moved to rod C.

Python Program for Tower of Hanoi

Move: 6

Finally, we will transfer the disc from position A to position C to complete the puzzle.

Python Program for Tower of Hanoi

Move: 7

Tower of Hanoi implementation in Python:

Code:

def tower__of__hanoi(number, start, aux, end):  
    if (number == 1):  
        print ('Moved disk 1 from rod {} to rod {}'.format (start, end))  
        return
    tower__of__hanoi(number - 1, start, end, aux)  
    print ('Moved disk {} from rod {} to rod {}'.format (number, start, end))  
    tower__of__hanoi(number - 1, aux, start, end)  


number = 3
tower__of__hanoi (number, 'A', 'B', 'C')

Output:

Moved disk 1 from rod A to rod C
Moved disk 2 from rod A to rod B
Moved disk 1 from rod C to rod B
Moved disk 3 from rod A to rod C
Moved disk 1 from rod B to rod A
Moved disk 2 from rod B to rod C
Moved disk 1 from rod A to rod C

Explanation

Here, the game's implementation was done using a recursive approach.

  1. The TowerOfHanoi() function requires four inputs.
    • Quantity of discs
    • source rod
    • supporting rod
    • target rod
  2. If the number of discs is 1, this first checks the condition, pushes the disc immediately to the destination rod, and then ends the function.
  3. The rest n-1 discs were then recursively moved from the source node to the supporting node utilizing the target rod as the auxiliary node.
  4. The final disc is then immediately transferred from the source rod to the supporting rod.
  5. Finally, using the source node, we have once more run the function recursively to transfer the rest n-1 rods from the supporting rod to the target rod.

Can the Tower of Hanoi be solved without recursion?

It's possible for anyone to have this thought. Yes, it is undoubtedly feasible. By using a binary solution strategy, where the n number of discs are encoded and represented as the numbers 0 - 2n, the tower of Hanoi problem can also be solved non-recursively.

The recursive solution's time complexity:

Tower of Hanoi's recursive solution has an O(2n) time complexity, wherein n is the number of discs.

Conclusion

In this article, we gained in-depth information about the Tower of Hanoi game and its Python recursive implementation. Along with thoroughly developing the game's concept, we also discovered a simple Python implementation.


Related Topics

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Python hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.