Home » Python » Python programs

# Python program Tower of Hanoi (modified)

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

Submitted by Anuj Singh, on June 30, 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.
- Disk cannot be transferred to peg B directly. It must be transferred to middle peg while moving from A to B or B to A.

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) = 2 Consider the case of shifting two disk : T(2) = 3*T(1) + 2 = 8 Consider the case of shifting three disk : T(3) = 3*T(2) + 2 = 26 . . . . T(n) = 3*T(n-1) + 2

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

So here is the code:

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

**Output:**

ENTER THE NUMBER OF DISKS: 14 NUMBER OF STEPS: 4782968 : 14

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.

Learn PCB Designing: PCB DESIGNING TUTORIAL