Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Created February 14, 2023 21:58
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 MishaelRosenthal/0bc701e2e2367d9da4c8f1754ca395f0 to your computer and use it in GitHub Desktop.
Save MishaelRosenthal/0bc701e2e2367d9da4c8f1754ca395f0 to your computer and use it in GitHub Desktop.
def move_one(source, destination):
towers_dict[destination].append(towers_dict[source].pop())
# print the movement and resulting towers
global number_of_steps
number_of_steps += 1
print("step", number_of_steps, "moved from", source, "to", destination)
print_towers()
def move_upper(number_of_disks, source, destination, helper_tower):
if(number_of_disks>0):
move_upper(number_of_disks-1, source=source, destination=helper_tower, helper_tower=destination)
move_one(source, destination)
move_upper(number_of_disks-1, source=helper_tower, destination=destination, helper_tower=source)
def print_towers():
spacing = " "
max_hight = 0
for name, tower in towers_dict.items():
max_hight = max(max_hight, len(tower))
for height in range(max_hight-1, -1, -1):
line = ""
for name, tower in towers_dict.items():
if(len(tower) > height):
line += (spacing + str(tower[height]))
else:
line += (spacing + " ")
print(line)
line = ""
for name, tower in towers_dict.items():
line += (spacing + "-")
print(line)
print()
# -------------------------------------- main code ------------------------------------------
# get input
print('How many disks')
number_of_disks = int(input())
# intialize
towers_dict = {"1": list(range(number_of_disks, 0, -1)), "2": [], "3": []}
print_towers()
number_of_steps = 0
# solve
move_upper(number_of_disks, source="1", destination="3", helper_tower="2")
print("Done!!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment