Tower of Hanoi in Python
2 min readFeb 5, 2023
Tower of Hanoi is a classic puzzle where the goal is to move a stack of n discs from the first peg to the last peg, subject to the restriction that you can only move one disc at a time and you cannot place a larger disc on top of a smaller one. Tower of Hanoi can be solved using recursion. Here is an example implementation in Python:
def tower_of_hanoi(n, source, auxiliary, target):
if n == 1:
print(f"Move disk 1 from peg {source} to peg {target}")
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from peg {source} to peg {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)
if __name__ == "__main__":
n = 3
tower_of_hanoi(n, "A", "B", "C")
Explanation:
- The
tower_of_hanoi
function takes the number of discs,n
, and the names of the source, auxiliary, and target pegs as input. - The base case of the recursion is when there is only one disk. In this case, the function simply prints the move to be made.
- For the recursive case, the function first solves the subproblem of moving
n-1
discs from the source to the auxiliary peg using the target as auxiliary. - Then, the function prints the move of the
nth
disk from the source to the target peg. - Finally, the function solves the subproblem of moving
n-1
discs from the auxiliary to the target peg using the source as auxiliary. - The
if __name__ == "__main__"
block is a special Python construct that only executes the code inside if the script is run directly (not imported as a module). - In the main block, the number of discs
n
is initialized to 3 and thetower_of_hanoi
function is called to solve the puzzle forn
discs.