gpt4 book ai didi

python - Towers of Hanoi Python——理解递归

转载 作者:太空狗 更新时间:2023-10-30 01:15:15 27 4
gpt4 key购买 nike

<分区>

我是 Python 的新手,目前正在学习有关汉诺塔和递归的教程。在他们给出这个例子之前,我认为我理解递归:

def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
#print(withPole)

def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)


moveTower(3,"A","B","C")

它打印出用 3 个圆盘解决汉诺塔问题的正确步骤:将磁盘从 A 移动到 B将磁盘从 A 移动到 C将磁盘从 B 移动到 C将磁盘从 A 移动到 B将磁盘从 C 移动到 A将磁盘从 C 移动到 B将磁盘从 A 移动到 B

我的问题是,它是怎么做到的?!有人可以检查代码行以便我了解它如何打印正确的 Action 吗?我主要对 fptp 的值如何从 ABC。对不起,如果这是一个广泛的问题!任何帮助将不胜感激!

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com