Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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