Files
python_test/hanoi/hanoi.py
T

49 lines
1.5 KiB
Python

def tower_of_hanoi(n, source, auxiliary, target):
"""
Solve the Tower of Hanoi puzzle with n disks.
Parameters:
n (int): The number of disks to move.
source (str): The starting peg.
auxiliary (str): An intermediate peg.
target (str): The destination peg.
Raises:
ValueError: If n is less than 1, indicating no disks to move.
"""
if n < 1:
raise ValueError("No disks to move. Please enter a positive integer.")
if n == 1:
print(f"Move disk 1 from {source} to {target}")
else:
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)
def prompt_for_integer():
"""
Prompts the user to enter a positive integer until a valid input is received.
Returns:
int: A positive integer entered by the user.
Raises:
ValueError: If the entered input is anything else, for instance a negative integer or a string.
"""
while True:
user_input = input("Please enter an integer: ")
try:
user_integer = int(user_input)
if user_integer > 0:
return user_integer
else:
print("The number must be positive.")
except ValueError:
print("Invalid literal for int() with base 10. Please enter an integer.")
if __name__ == "__main__":
user_integer = prompt_for_integer()
tower_of_hanoi(user_integer, 'A', 'B', 'C')