递归应用:汉诺塔

# -*- encoding: utf-8 -*-
"""
@File    : datastruck.py
@Time    : 2021-07-04 18:19
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
def movedisk(diskindex, fromtower, targettower):
    print("Move disk {} from {} to {}".format(diskindex, fromtower, targettower))

def moveTower(n, fromtower, withtower , targettower):
    if n == 1 :
        movedisk(1, fromtower, targettower)
    else:
        moveTower(n - 1, fromtower, targettower, withtower )
        movedisk(n, fromtower, targettower)
        moveTower(n - 1, withtower, fromtower , targettower)
if __name__ == '__main__':
    moveTower(3, "A", "B", "C")

result

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
上一篇:Linux 查看硬盘类型


下一篇:苹果mac磁盘清理工具:Pro Disk Cleaner