Omarbetade tester och tydligare funktions- och variabelnamn
This commit is contained in:
+39
-24
@@ -1,33 +1,48 @@
|
||||
|
||||
def hanoi(n, source, auxiliary, target):
|
||||
# Example usage:
|
||||
# hanoi(3, 'A', 'B', 'C')
|
||||
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:
|
||||
print(f"No disks, nothing to do")
|
||||
return
|
||||
raise ValueError("No disks to move. Please enter a positive integer.")
|
||||
|
||||
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)
|
||||
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 get_hanoi_input():
|
||||
# Returns a positive integer, otherwise throws an exception
|
||||
while True:
|
||||
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)
|
||||
return user_integer
|
||||
if user_integer > 0:
|
||||
return user_integer
|
||||
else:
|
||||
print("The number must be positive.")
|
||||
except ValueError:
|
||||
print("That's not a valid integer. Please try again.")
|
||||
print("Invalid literal for int() with base 10. Please enter an integer.")
|
||||
|
||||
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')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
user_integer = prompt_for_integer()
|
||||
tower_of_hanoi(user_integer, 'A', 'B', 'C')
|
||||
|
||||
Reference in New Issue
Block a user