In this shot, we’ll look at the tower of Hanoi problem and how to solve the problem in Python.
Let’s start by discussing what the tower of Hanoi problem is. It is a mathematical problem that involves three vertical rods and
n circular discs. In their original state, the discs are stacked in order on the first rod, with the largest at the bottom of the pile and the smallest at the top. The goal of the problem is to move the entire stack to the final rod with the order remaining constant. However, the solution has to abide by some constraints:
Let’s take a look at how three discs would be moved from the first to the last rod in the slides below.
We can find the code of this given problem below:
def TowerOfHanoi(n, start_rod, end_rod, transition_rod): ## base case for only one disc remaining if n==1: print "Move disk 1 from rod",start_rod,"to rod",end_rod return ## Recursive call for to move the top disc in a stack of 2 TowerOfHanoi(n-1, start_rod, transition_rod, end_rod) print "Move disk",n,"from rod",start_rod,"to rod",end_rod ## Recursive call for to move the top disc in a stack of 3 TowerOfHanoi(n-1, transition_rod, end_rod, start_rod) n = 3 TowerOfHanoi(n,'A','C','B')
View all Courses