Created
February 14, 2023 21:58
-
-
Save MishaelRosenthal/0bc701e2e2367d9da4c8f1754ca395f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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