Home » Python » Python programs

# Python program for Tower of Hanoi

Here, we are going to implement a **python program for Tower of Hanoi**.

Submitted by Anuj Singh, on June 28, 2019

You are challenged for a challenge to find the number of moves required to move a stack of disks from one peg to another peg. Wait for a second, it sounds easy? Let’s find are what is going on and in this article, we are introducing a chapter of **"TOWER OF HANOI"**.

You are given with a stack of n disks on a peg arranges as largest is at the bottom and smallest is at the top. We are required to shift this whole stack to another peg (total three pegs, two are empty initially) with considering the following rule:

- No larger disk can be placed over a smaller one.
- One disk at a time.

The problem is looking easy but it's not. The way we are going to tackle it is recursion. The problem is simple when you see it from recursion perspective.

Key: The number of steps required to shift the stack is exactly equal to the twice of steps for shifting the stack of one less disk(The largest one) plus one step.

Consider the case of shifting one disk : T(1) = 1 Consider the case of shifting two disk : T(2) = 2*T(1) + 1 = 3 Consider the case of shifting three disk : T(3) = 2*T(2) + 1 = 7 . . . . T(n) = 2*T(n-1) + 1

Implementing this formula now in our python program is our next goal of solving this.

So here is the code:

def hanoi(x): if x == 1: return 1 else: return 2*hanoi(x-1) + 1 x = int(input("ENTER THE NUMBER OF DISKS: ")) print('NUMBER OF STEPS: ', hanoi(x))

**Output:**

ENTER THE NUMBER OF DISKS: 5 NUMBER OF STEPS: 31

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.