gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:11 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 为什么这个递归代码有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com