Skip to content

Instantly share code, notes, and snippets.

@douglasgoodwin
Created February 25, 2020 20:03
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 douglasgoodwin/8632cba6bed9b00aebe8755b192a5326 to your computer and use it in GitHub Desktop.
Save douglasgoodwin/8632cba6bed9b00aebe8755b192a5326 to your computer and use it in GitHub Desktop.
h = 4
A = []
B = []
C = []
for i in range(1,h+1):
A.append(i)
A.reverse()
towers = {"A":A,"B":B,"C":C}
def TowerOfHanoi(h, from_rod, to_rod, aux_rod):
# we decrease h each time through,
# testing each possible disk
if h >= 1:
# try one strategy: (from, aux, to)
TowerOfHanoi(h-1,from_rod,aux_rod,to_rod)
# print("move disk",h,"from",from_rod,"to",to_rod)
f = towers[from_rod]
t = towers[to_rod]
mv = f.pop()
t.append(mv)
print(A,B,C)
# REVERSE the strategy: (aux, to, from)!
TowerOfHanoi(h-1,aux_rod,to_rod,from_rod)
TowerOfHanoi(h=h,from_rod="A",to_rod="C",aux_rod="B")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment