Created
April 13, 2023 15:12
-
-
Save vrdhn/97d262fef0b5b5aaaa9bf078f9ef5703 to your computer and use it in GitHub Desktop.
hanoi.py
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
from collections import namedtuple | |
## Convention | |
## 4 3 2 1 size discs are stored as [ 4,3,2,1 ] | |
## name -> string | |
## discs -> sparse reverse sorted array of number | |
Peg = namedtuple('Peg', ['name', 'discs']) | |
MOVES = 0 | |
def mv( s , t, o ): | |
""" move SINGLE disc """ | |
global MOVES | |
d = s.discs.pop() | |
if len(t.discs) > 0: | |
assert d < t.discs[-1] | |
t.discs.append(d) | |
MOVES += 1 | |
print(f"MOVE({MOVES}): {d} from {s.name} ==> {t.name}") | |
for z in sorted([s,t,o],key= lambda x : x.name): | |
print(f" {z}") | |
## [ 1 , 2, 3,4 ] | |
def hanoi(tomove, source, target, temp): | |
if tomove < 0: | |
return | |
elif tomove == 1 : | |
mv(source,target,temp) | |
else: | |
hanoi(tomove - 1 , source, temp, target) | |
mv( source, target ,temp) | |
hanoi(tomove - 1 , temp, target, source ) | |
def main(n): | |
a = Peg( 'A', list(reversed(range(1, n + 1)))) | |
b = Peg( 'B', []) | |
c = Peg( 'C', []) | |
hanoi(n, a,b,c) | |
print("--- SOLVED ---") | |
debug_dump(a,b,c) | |
def debug_dump(s, t, p): | |
print("** SOURCE: ", s) | |
print("** TARGET: ", t) | |
print("** TEMP : ", p) | |
main(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment