【发布时间】:2016-12-22 02:05:11
【问题描述】:
我为 Hanoi Towers 问题找到了 Python 代码 online。该代码有效,但我很难理解它。这里是:
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
# move disk from source peg to target peg
if source:
target.append(source.pop())
# move tower of size n-1 from helper to target
hanoi(n - 1, helper, source, target)
source = [2, 1]
target = []
helper = []
hanoi(len(source), source, helper, target)
print (source, helper, target)
我对最后一部分有困难:
hanoi(n - 1, helper, source, target)
据我所知,发生的唯一移动是通过 target.append(source.pop()) 行。当我们使用 [2,1] 的简单列表时,在我们将 1 移动到目标列表后,它会以某种方式将 1 移动到辅助列表,但是如何???
我的看法,下面是程序运行的方法:它到达n = 0,什么都不做,返回n = 1,将1移动到目标,然后它到达我的难点,并执行
hanoi(n - 1, helper, source, target)
但由于 n-1 = 0,它什么也不做,然后它应该继续移动到 n = 2,与 源 = [2],助手 = [],目标 = [1]。但是当我在程序上使用打印时,我看到在我的困难点之后和 n = 2 之前,该函数确实将 1 移动到了助手,情况是 source = [2], helper = [1], target = []
即使 n = 0,它是如何做到的?它有一个条件,只有当 n>0 时它才会执行?我如何使用打印来查看那一刻发生了什么?
【问题讨论】:
-
诀窍在于参数的顺序:您可以看到助手和目标交换。
-
您是否尝试过添加一些
prints,或者使用例如pythontutor.com 可视化发生了什么? -
@DanielRoseman 仍然,n = 0,这意味着条件 n > 0 不满足!当 n = 0 时,该函数不应该什么都不做!
-
@blz 如果
n <= 0,函数只返回None,是的。 -
@jonrsharpe 然而,当我们在 n = 1 的情况下执行 hanoi(n - 1, helper, source, target) 行时,它会以某种方式将 1 从目标移动到助手
标签: python python-3.x recursion towers-of-hanoi