Skip to content

Instantly share code, notes, and snippets.

@vrdhn
Created April 13, 2023 15:12
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 vrdhn/97d262fef0b5b5aaaa9bf078f9ef5703 to your computer and use it in GitHub Desktop.
Save vrdhn/97d262fef0b5b5aaaa9bf078f9ef5703 to your computer and use it in GitHub Desktop.
hanoi.py
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