我对 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
and的值如何tp
从A
toB
变为 to感到困惑C
。对不起,如果这是一个广泛的问题!任何帮助将不胜感激!