我完全是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")
以下是解决三个圆盘汉诺塔问题的正确移动步骤:
从A移动圆盘到B 从A移动圆盘到C 从B移动圆盘到C 从A移动圆盘到B 从C移动圆盘到A 从C移动圆盘到B 从A移动圆盘到B
您的问题是,它是如何做到这一点的?有人可以看一下代码行,以便我了解它如何打印正确的移动步骤吗?我主要困惑于fp和tp的值如何从A更改为B再到C。抱歉如果这是一个比较广泛的问题!任何帮助都将不胜感激!
print(height, fromPole, toPole, withPole)
放在顶部,看看会发生什么! - jonrsharpe