在python中累积递归函数的结果

时间:2015-02-02 20:54:04

标签: python recursion

考虑使用以下函数来置换列表中的数字:

def permute(numbers, N=0):
    # base case
    if N == len(numbers):
        print numbers
        return

    for i in range(len(numbers)-N):

        # swapping relevant elements
        element=numbers.pop(N+i)
        numbers.insert(N,element)

        # recursive call
        permute(numbers, N+1)

        # swapping back relevant elements when backtracking
        element=numbers.pop(N)
        numbers.insert(N+i,element)


numbers=[1,2,3]
permute(numbers)

为什么当我运行上面的代码时,它产生正确的输出:

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

但是当我试图将结果累积到列表时:

def permute(numbers, permutations, N=0):
    # base case
    if N == len(numbers):
        print numbers
        permutations.append(numbers)
        return

    for i in range(len(numbers)-N):

        # swapping relevant elements
        element=numbers.pop(N+i)
        numbers.insert(N,element)

        # recursive call
        permute(numbers, permutations, N+1)

        # swapping back relevant elements when backtracking
        element=numbers.pop(N)
        numbers.insert(N+i,element)


numbers=[1,2,3]
permutations=[]
permute(numbers, permutations)

print "-----------"
for p in permutations:
    print p

输出是这样的:

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

不完全符合我的预期...

1 个答案:

答案 0 :(得分:3)

您追加到permutations的所有项目实际上都是相同的列表。改变一个会改变所有其他人。最简单的解决方法是在添加列表之前复制列表,因此对numbers的未来更改不会影响已经附加的结果。

def permute(numbers, permutations, N=0):
    # base case
    if N == len(numbers):
        print numbers
        permutations.append(numbers[:])
        return

结果:

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