河内之塔Python:使用局部和全局变量可以改变输出

时间:2018-01-14 21:34:07

标签: python python-3.x towers-of-hanoi

所以,我正在使用Python中的Tower of Hanoi算法,将3个堆栈表示为列表。这是代码:

def move(stack, inter_stack, final_stack):
    disk=stack.pop()
    final_stack.append(disk)
    print(stack, inter_stack, final_stack)

def moveDisks(n,start,end,inter):
    if n==1:
        move(start, inter, end)
    else:
        moveDisks(n-1,start,inter,end)
        move(start, inter, end)
        moveDisks(n-1,inter,end,start)

n = input("Enter the # of blocks: ")
n = int(n)
start=[]
inter=[]
end=[]
for i in range(n):
   start=start+[n-i]
moveDisks(n,start,end,inter)

如果我使用n = 3运行此代码,Python给出的结果如下:

[3, 2] [] [1]
[3] [1] [2]
[] [3] [2, 1]
[] [2, 1] [3]
[2] [3] [1]
[] [1] [3, 2]
[] [] [3, 2, 1]

在此输出中可以清楚地看到堆栈出现故障。但是,如果我替换

print(stack, inter_stack, final_stack)

print(start, inter, end)

代码以正确的顺序输出堆栈:

[3, 2] [] [1]
[3] [2] [1]
[3] [2, 1] []
[] [2, 1] [3]
[1] [2] [3]
[1] [] [3, 2]
[] [] [3, 2, 1]

为什么会发生这种情况,考虑到两组变量都带有相同的值,第二种方式只使用全局变量?

1 个答案:

答案 0 :(得分:1)

当你递归时,用这两个调用改变堆栈的含义:

moveDisks(n - 1, start, inter, end)
moveDisks(n - 1, inter, end, start)

请注意更改订单。因此在move()

print(stack, inter_stack, final_stack)

每次都会引用不同的列表。