Files
python_test/hanoi/hanoi.py
T
2024-07-12 16:59:21 +02:00

33 lines
1.1 KiB
Python

def hanoi(n, source, auxiliary, target):
# Example usage:
# hanoi(3, 'A', 'B', 'C')
if n < 1:
print(f"No disks, nothing to do")
return
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
# Move n-1 disks from source to auxiliary, so they are out of the way
hanoi(n - 1, source, target, auxiliary)
# Move the nth disk from source to target
print(f"Move disk {n} from {source} to {target}")
# Move the n-1 disks that we left on auxiliary to target
hanoi(n - 1, auxiliary, source, target)
def get_hanoi_input():
# Returns a positive integer, otherwise throws an exception
while True:
user_input = input("Please enter an integer: ")
try:
user_integer = int(user_input)
return user_integer
except ValueError:
print("That's not a valid integer. Please try again.")
if __name__== "__main__":
# Call the new function to get the input
user_integer = get_hanoi_input()
# Now call hanoi with the obtained integer
hanoi(user_integer, 'A', 'B', 'C')