From 735c72f313948940efc03a47ee8b16c783a606b6 Mon Sep 17 00:00:00 2001 From: Abhay Pandey <116704975+Aloneking789@users.noreply.github.com> Date: Fri, 6 Oct 2023 23:31:05 +0530 Subject: [PATCH] tower_of_hanoi.py Fixes #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. --- tower_of_hanoi.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tower_of_hanoi.py diff --git a/tower_of_hanoi.py b/tower_of_hanoi.py new file mode 100644 index 000000000000..c4954ed92790 --- /dev/null +++ b/tower_of_hanoi.py @@ -0,0 +1,23 @@ +def tower_of_hanoi(n, source_peg, auxiliary_peg, target_peg): + if n == 1: + print(f"Move disk 1 from {source_peg} to {target_peg}") + return + tower_of_hanoi(n - 1, source_peg, target_peg, auxiliary_peg) + print(f"Move disk {n} from {source_peg} to {target_peg}") + tower_of_hanoi(n - 1, auxiliary_peg, source_peg, target_peg) + +# Input from the user +n = int(input("Enter the number of disks: ")) +source_peg = input("Enter the name of the source peg (e.g., 'A'): ").strip().upper() +auxiliary_peg = input("Enter the name of the auxiliary peg (e.g., 'B'): ").strip().upper() +target_peg = input("Enter the name of the target peg (e.g., 'C'): ").strip().upper() + +# Ensure peg names are distinct +while source_peg == auxiliary_peg or source_peg == target_peg or auxiliary_peg == target_peg: + print("Peg names must be distinct. Please enter again.") + source_peg = input("Enter the name of the source peg: ").strip().upper() + auxiliary_peg = input("Enter the name of the auxiliary peg: ").strip().upper() + target_peg = input("Enter the name of the target peg: ").strip().upper() + +# Call the tower_of_hanoi function with user input +tower_of_hanoi(n, source_peg, auxiliary_peg, target_peg)