Skip to content

Instantly share code, notes, and snippets.

@pkutaj
Created December 26, 2022 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkutaj/0435a339bf7a601026baedb291c9c4d1 to your computer and use it in GitHub Desktop.
Save pkutaj/0435a339bf7a601026baedb291c9c4d1 to your computer and use it in GitHub Desktop.
RC1-16.02-Towers-of-Hanoi.py
move_count = 0
def move_disk(remaining_disks, source, target):
global move_count
print(f"STEP#{move_count+1}\n"
f"\t~~> Disk #{remaining_disks}; {source} > {target}")
def count_move():
global move_count
move_count += 1
def build_hanoi(remaining_disks, source, target, temp):
if remaining_disks == 0:
return 0
build_hanoi(
remaining_disks-1, source, temp, target)
move_disk(remaining_disks, source, target)
count_move()
build_hanoi(
remaining_disks - 1, temp, target, source)
def test_build_hanoi():
remaining_disks = int(
input("How many disks you want to solve for (max 8) ?: "))
if remaining_disks > 8:
raise ValueError("You can't play with more than 8 disks. \n"
"The printer would run out of print.")
print(
f"\t~~> These are the moves for {remaining_disks} disks \n"
f"\t~~> The top is disk#1, the bottom is the disk#{remaining_disks} \n"
)
source = "A"
temp = "B"
target = "C"
build_hanoi(remaining_disks, source, target, temp)
assert move_count == (2 ** remaining_disks) - 1
print(f"TOTAL\n"
f"\t~~> you required {move_count} moves")
if __name__ == "__main__":
print(" TOWERS OF HANOI SOLUTION PRINTER ".center(80, "-"))
test_build_hanoi()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment