Last active
December 7, 2022 16:57
-
-
Save pylover/98b49e80ebc00167f5862c3a237a3f0b to your computer and use it in GitHub Desktop.
Tower of Hanoi using Python3
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
#! /usr/bin/env python3 | |
""" | |
Move: 65536 | |
| | | | |
| | 1 | |
| | 2 | |
| | 3 | |
| | 4 | |
| | 5 | |
| | 6 | |
| | 7 | |
| | 8 | |
| | 9 | |
| | 10 | |
| | 11 | |
| | 12 | |
| | 13 | |
| | 14 | |
| | 15 | |
| | 16 | |
-------------------------------------- | |
A B C | |
""" | |
MAXRINGS = 16 | |
SPACER = 16 | |
SP = ' ' * SPACER | |
celllen = len(str(MAXRINGS)) | |
moves = 0 | |
a = list(range(MAXRINGS, 0, -1)) | |
b = [] | |
c = [] | |
def getcell(t, i): | |
if len(t) >= i: | |
return t[i - 1] | |
return '|' | |
def print_towers(): | |
global moves | |
i = MAXRINGS + 1 | |
moves += 1 | |
print(f'\033[{MAXRINGS + 7}AMove: {moves}\n') | |
while i: | |
print(f'{getcell(a, i): >{celllen}}{SP}{getcell(b, i): >{celllen}}{SP}' | |
f'{getcell(c, i): >{celllen}}') | |
i -= 1 | |
print('-' * (SPACER * 2 + 3 * celllen)) | |
print(f'{"A": >{celllen}}{SP}{"B": >{celllen}}{SP}{"C": >{celllen}}\n\n') | |
def move(n, ta, tb, tc): | |
if n == 1: | |
tb.append(ta.pop()) | |
print_towers() | |
return | |
move(n-1, ta, tc, tb) | |
tb.append(ta.pop()) | |
print_towers() | |
move(n-1, tc, tb, ta) | |
if __name__ == '__main__': | |
print('\n' * (MAXRINGS + 10)) | |
try: | |
print_towers() | |
move(MAXRINGS, a, c, b) | |
except KeyboardInterrupt: | |
print('\n' * MAXRINGS) | |
print(f'Terminated by user') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment