【发布时间】:2014-05-31 05:13:39
【问题描述】:
我对 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
我的问题是,它是如何做到的?!有人可以检查代码行,以便我了解它如何打印正确的动作吗?我主要对fp 和tp 的值如何从A 更改为B 到C 感到困惑。对不起,如果这是一个广泛的问题!任何帮助将不胜感激!
【问题讨论】:
-
也许这个答案有帮助:stackoverflow.com/a/1223334/3440545
-
我建议在顶部粘贴
print(height, fromPole, toPole, withPole)看看会发生什么! -
非常感谢所有回答的人!现在对我的理解更有信心了:)
标签: python algorithm recursion towers-of-hanoi