|
| 1 | +def tower_of_hanoi(n: int, source_peg: str, auxiliary_peg: str, target_peg: str) -> None: |
| 2 | + """ |
| 3 | + Solve the Tower of Hanoi problem for 'n' disks. |
| 4 | +
|
| 5 | + Args: |
| 6 | + n (int): The number of disks to move. |
| 7 | + source_peg (str): The name of the source peg. |
| 8 | + auxiliary_peg (str): The name of the auxiliary peg. |
| 9 | + target_peg (str): The name of the target peg. |
| 10 | +
|
| 11 | + Returns: |
| 12 | + None |
| 13 | +
|
| 14 | + Examples: |
| 15 | + >>> tower_of_hanoi(1, 'A', 'B', 'C') |
| 16 | + Move disk 1 from A to C |
| 17 | +
|
| 18 | + >>> tower_of_hanoi(3, 'A', 'B', 'C') |
| 19 | + Move disk 1 from A to C |
| 20 | + Move disk 2 from A to B |
| 21 | + Move disk 1 from C to B |
| 22 | + Move disk 3 from A to C |
| 23 | + Move disk 1 from B to A |
| 24 | + Move disk 2 from B to C |
| 25 | + Move disk 1 from A to C |
| 26 | + """ |
| 27 | + if n == 1: |
| 28 | + print(f"Move disk 1 from {source_peg} to {target_peg}") |
| 29 | + return |
| 30 | + tower_of_hanoi(n - 1, source_peg, target_peg, auxiliary_peg) |
| 31 | + print(f"Move disk {n} from {source_peg} to {target_peg}") |
| 32 | + tower_of_hanoi(n - 1, auxiliary_peg, source_peg, target_peg) |
| 33 | + |
| 34 | +# Input from the user |
| 35 | +if __name__ == "__main__": |
| 36 | + n = int(input("Enter the number of disks: ")) |
| 37 | + source_peg = input("Enter the name of the source peg (e.g., 'A'): ").strip().upper() |
| 38 | + auxiliary_peg = input("Enter the name of the auxiliary peg (e.g., 'B'): ").strip().upper() |
| 39 | + target_peg = input("Enter the name of the target peg (e.g., 'C'): ").strip().upper() |
| 40 | + |
| 41 | + # Ensure peg names are distinct |
| 42 | + while source_peg == auxiliary_peg or source_peg == target_peg or auxiliary_peg == target_peg: |
| 43 | + print("Peg names must be distinct. Please enter again.") |
| 44 | + source_peg = input("Enter the name of the source peg: ").strip().upper() |
| 45 | + auxiliary_peg = input("Enter the name of the auxiliary peg: ").strip().upper() |
| 46 | + target_peg = input("Enter the name of the target peg: ").strip().upper() |
| 47 | + |
| 48 | + # Call the tower_of_hanoi function with user input |
| 49 | + tower_of_hanoi(n, source_peg, auxiliary_peg, target_peg) |
| 50 | + |
| 51 | +For more: |
| 52 | + https://github.com/TheAlgorithms/Python |
| 53 | + https://en.wikipedia.org/wiki/Tower_of_Hanoi |
0 commit comments