汉诺塔python 实现 height=5 towers=[[] for _ in range(3)] towers[0]=list(range(height,0,-1)) from time import sleep from IPython.display import clear_output def display(): clear_output(True) print('{:^12}'.format('||')*3) for level in range(height,0,-1): for t in towers: try: print('{:^12}'.format('=='*t[level-1]),end='') except IndexError: print('{:^12}'.format('||'),end='') print() print('-'*36) sleep(1) def move(frm,to): towers[to].append(towers[frm].pop(-1)) display() def hanoi(frm,to,using,levels): if levels==1: move(frm,to) else: hanoi(frm,using,to,levels-1) move(frm,to) hanoi(using,to,frm,levels-1) hanoi(0,2,1,height)