×

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

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 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.

How to print in the same line in Python?

How to print in the same line in python By default, the print function in Python takes us to the next line and prints the desired statement in the output. In this...

5 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

How to convert integer to float 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...

5 minutes read.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.