Write a Program to Implement Tower of Hanoi using Python.
SOURCE CODE :
def tower_of_hanoi(num, source, aux, target):
"""
num (int): Number of disks.
source (str): The name of the source tower.
aux (str): The name of the auxiliary tower.
target (str): The name of the target tower.
"""
if num == 1:
print(f"Move disk 1 from {source} to {target}")
return
# Move num-1 disks from source to auxiliary
tower_of_hanoi(num - 1, source, target, aux)
print(f"Move disk {num} from {source} to {target}")
# Move the num-1 disks from auxiliary to target
tower_of_hanoi(num - 1, aux, source, target)
# Example usage
num_disks = 3
tower_of_hanoi(num_disks, "A", "B", "C")
OUTPUT :
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
๐ป Run This Python Program
Write a Program to Implement Tower of Hanoi using Python.
The selected Python program is loaded
automatically into the editor.
Edit the program, provide input if required
and click Run.
The compiler is embedded using OneCompiler.
Your Python program runs inside the embedded
Python environment; Study Glance does not execute
Python code directly on your web server.
If the program asks for input (for example the
starting node), type the value in the
STDIN box before clicking Run.