【发布时间】:2021-06-01 07:22:11
【问题描述】:
所以我有一个递归函数,我用不同的参数调用了 2 次,但我第二次调用它时,它没有给出正确的结果,它只在我第一次而不是第二次调用它时给出正确的结果。也许是内存或缓存问题?
def m(n):
s= [int(char) for char in str(n)]
product = 1
for x in s:
product *= x
return product
i = 0
def persistence(n):
global i
if len(str(n)) == 1:
return i
else:
j = m(n)
i+=1
s = persistence(j)
return s
print(persistence(39))
print(persistence(4)) #returns 3 when called with the top one but 0 when called alone
【问题讨论】:
-
那是因为您使用 i 作为全局变量。再次执行持久化时,i变量值不为0
-
presistence(4)将在if分支中返回i。如果这是第一次调用persistence,那么i就是0。如果您首先使用39调用它,该调用将转到else分支,该分支会更改i变量。当您使用4调用它时,它将不再是0。这就是为什么你应该避免全局的、可变的状态
标签: python python-3.x recursion memory