Skip to content

Commit 735c72f

Browse files
authored
tower_of_hanoi.py
Fixes TheAlgorithms#9936 This code prompts the user to input the number of disks and the names of the source, auxiliary, and target pegs. It also checks that the peg names are distinct. Then, it calls the tower_of_hanoi function to solve the Tower of Hanoi problem based on the user's input.
1 parent 795e97e commit 735c72f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Diff for: tower_of_hanoi.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def tower_of_hanoi(n, source_peg, auxiliary_peg, target_peg):
2+
if n == 1:
3+
print(f"Move disk 1 from {source_peg} to {target_peg}")
4+
return
5+
tower_of_hanoi(n - 1, source_peg, target_peg, auxiliary_peg)
6+
print(f"Move disk {n} from {source_peg} to {target_peg}")
7+
tower_of_hanoi(n - 1, auxiliary_peg, source_peg, target_peg)
8+
9+
# Input from the user
10+
n = int(input("Enter the number of disks: "))
11+
source_peg = input("Enter the name of the source peg (e.g., 'A'): ").strip().upper()
12+
auxiliary_peg = input("Enter the name of the auxiliary peg (e.g., 'B'): ").strip().upper()
13+
target_peg = input("Enter the name of the target peg (e.g., 'C'): ").strip().upper()
14+
15+
# Ensure peg names are distinct
16+
while source_peg == auxiliary_peg or source_peg == target_peg or auxiliary_peg == target_peg:
17+
print("Peg names must be distinct. Please enter again.")
18+
source_peg = input("Enter the name of the source peg: ").strip().upper()
19+
auxiliary_peg = input("Enter the name of the auxiliary peg: ").strip().upper()
20+
target_peg = input("Enter the name of the target peg: ").strip().upper()
21+
22+
# Call the tower_of_hanoi function with user input
23+
tower_of_hanoi(n, source_peg, auxiliary_peg, target_peg)

0 commit comments

Comments
 (0)