使用python实现递归版汉诺塔示例(汉诺塔递归算法)

秋天来啦!秋天来啦!田野里就是美丽的图画。花生躲在地下,包着红色的毛毯,住在土黄色的房间里睡大觉。玉米姐姐穿着绿色的裙子,在叶子上跳舞,南瓜爷爷鼓着金黄色的大肚子,坐着高级的南瓜车,一边看风景一边享受。西红柿露出火红火红的脸蛋,正对着我们微笑。谁使秋天这样美?看,田野里的菊花做出了回答,菊花顶着一个爆炸头,在微风中轻轻摇动,好像在说:是勤劳的人们画出了秋天的图画。

利用python实现的汉诺塔。带有图形演示


from time import sleep

def disp_sym(num, sym):
print(sym*num, end='')

#recusion
def hanoi(a, b, c, n, tray_num):
if n == 1:
move_tray(a, c)
disp(tray_num)
sleep(0.7)

else:
hanoi(a, c, b, n-1, tray_num)
move_tray(a, c)
disp(tray_num)
sleep(0.7)
hanoi(b, a, c, n-1, tray_num)

def move_tray(a, b):
for i in a:
if i != 0:
for j in b:
if j != 0:
b[b.index(j) - 1] = i
a[a.index(i)] = 0
return
b.append(i)
b.pop(0)
a[a.index(i)] = 0
returndef disp(tray_num):
global a, b, c
for i in range(tray_num):
for j in ['a', 'b', 'c']:
disp_sym(5, ' ')
eval('disp_sym(tray_num - ' + j + "[i], ' ')")
eval('disp_sym(' + j + "[i], '=')")
disp_sym(1, '|')
eval('disp_sym(' + j + "[i], '=')")
eval('disp_sym(tray_num - ' + j + "[i], ' ')")

print()

print('---------------------------------------------------------------------------')

tray_num=int(input("Please input the number of trays:"))
tray=[]
for i in range(tray_num):
tray.append(i + 1)
a=[0]*tray_num
b=a[:]
c=a[:]

a = tray[:]
disp(tray_num)
hanoi(a, b, c, tray_num, tray_num)

本文使用python实现递归版汉诺塔示例(汉诺塔递归算法)到此结束。岁月,是一首诗,一首蕴含丰富哲理的诗,岁月是一峰骆驼,驮着无数人的梦想。谢谢大家支持!

标签: 汉诺 python