fork download
  1. def tower_of_hanoi(n, source, target, auxiliary, move_counter):
  2. """
  3. - Srini Raj
  4. Recursively solves the Tower of Hanoi puzzle for n rings.
  5.  
  6. Parameters:
  7. n : The number of rings.
  8. source : The starting tower.
  9. target : The destination tower.
  10. auxiliary : The auxiliary tower.
  11. move_counter: A single-item list to keep track of move numbering.
  12. """
  13. if n == 1:
  14. move_counter[0] += 1
  15. print(f"{move_counter[0]}. Move Ring 1 from {source} to {target}.")
  16. return
  17.  
  18. # Move n-1 rings from the source to the auxiliary tower.
  19. tower_of_hanoi(n - 1, source, auxiliary, target, move_counter)
  20.  
  21. # Move the nth (largest) ring from the source to the target tower.
  22. move_counter[0] += 1
  23. print(f"{move_counter[0]}. Move Ring {n} from {source} to {target}.")
  24.  
  25. # Move the n-1 rings from the auxiliary tower to the target tower.
  26. tower_of_hanoi(n - 1, auxiliary, target, source, move_counter)
  27.  
  28. def main():
  29. try:
  30. n = int(input("Enter the number of rings: "))
  31. if n < 1:
  32. raise ValueError("Number of rings must be at least 1.")
  33. except ValueError as e:
  34. print("Invalid input:", e)
  35. return
  36.  
  37. print(f"\nTower of Hanoi solution for {n} rings:\n")
  38. move_counter = [0] # Using a list for a mutable move counter
  39. tower_of_hanoi(n, "Tower 1", "Tower 3", "Tower 2", move_counter)
  40.  
  41. if __name__ == "__main__":
  42. main()
Success #stdin #stdout 0.08s 14172KB
stdin
5
stdout
Enter the number of rings: 
Tower of Hanoi solution for 5 rings:

1. Move Ring 1 from Tower 1 to Tower 3.
2. Move Ring 2 from Tower 1 to Tower 2.
3. Move Ring 1 from Tower 3 to Tower 2.
4. Move Ring 3 from Tower 1 to Tower 3.
5. Move Ring 1 from Tower 2 to Tower 1.
6. Move Ring 2 from Tower 2 to Tower 3.
7. Move Ring 1 from Tower 1 to Tower 3.
8. Move Ring 4 from Tower 1 to Tower 2.
9. Move Ring 1 from Tower 3 to Tower 2.
10. Move Ring 2 from Tower 3 to Tower 1.
11. Move Ring 1 from Tower 2 to Tower 1.
12. Move Ring 3 from Tower 3 to Tower 2.
13. Move Ring 1 from Tower 1 to Tower 3.
14. Move Ring 2 from Tower 1 to Tower 2.
15. Move Ring 1 from Tower 3 to Tower 2.
16. Move Ring 5 from Tower 1 to Tower 3.
17. Move Ring 1 from Tower 2 to Tower 1.
18. Move Ring 2 from Tower 2 to Tower 3.
19. Move Ring 1 from Tower 1 to Tower 3.
20. Move Ring 3 from Tower 2 to Tower 1.
21. Move Ring 1 from Tower 3 to Tower 2.
22. Move Ring 2 from Tower 3 to Tower 1.
23. Move Ring 1 from Tower 2 to Tower 1.
24. Move Ring 4 from Tower 2 to Tower 3.
25. Move Ring 1 from Tower 1 to Tower 3.
26. Move Ring 2 from Tower 1 to Tower 2.
27. Move Ring 1 from Tower 3 to Tower 2.
28. Move Ring 3 from Tower 1 to Tower 3.
29. Move Ring 1 from Tower 2 to Tower 1.
30. Move Ring 2 from Tower 2 to Tower 3.
31. Move Ring 1 from Tower 1 to Tower 3.