1
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
4

1 回答 1

1

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

于 2013-04-15T21:17:17.570 回答