为什么这个递归代码有效?

时间:2013-04-15 21:13:55

标签: python function recursion arguments

def permutation(li,result=[]):
    print(li, result)               # I added this print statement as a diagnostic.
    if li == [] or li == None:      # As coded, I expected each recursive call to
        return                      # reinitialize 'result=[]' because there is no
                                    # second argument being passed in the recursive
    if len(li) == 1:                # call below.
        result.append(li[0])
        print(''.join(result))
        result.pop()
        return

    for i in range(0,len(li)):
        result.append(li[i])
        permutation(li[:i] + li[i+1:])          # I would have thought that the
       #permutation(li[:i] + li[i+1:], result)  # recursive call needed to be this.
        result.pop()        

test=list('123')
permutation(test)

结果:

['1', '2', '3'] []
['2', '3'] ['1']
['3'] ['1', '2']
123
['2'] ['1', '3']
132
['1', '3'] ['2']
['3'] ['2', '1']
213

1 个答案:

答案 0 :(得分:1)

因为resultmutable列表。简而言之,如果您将项目附加到列表,该项目仍然存在,除非列表或项目是垃圾收集。在您的代码中,result指向被声明为permutation函数的默认参数的相同列表对象。每次调用result函数时,都不会为permutation构建新列表。因为您为每个排列推送/弹出项目,您可能会认为(看起来像)您的函数是“无状态”,但事实并非如此。