Python 如何修复递归函数
我正在尝试编写一个递归函数,该函数将整数作为参数,并返回整数中求和为10的数对。例如,findPairs(28164730)将返回3,因为2+8=10、6+4=10和7+3=10。Python 如何修复递归函数,python,recursion,Python,Recursion,我正在尝试编写一个递归函数,该函数将整数作为参数,并返回整数中求和为10的数对。例如,findPairs(28164730)将返回3,因为2+8=10、6+4=10和7+3=10。 这就是我的代码现在的样子: def find(x): x = str(x) count = 0 if str((10 - int(x[0]))) in x: count = count + 1 x = x[1:] find(x) elif
这就是我的代码现在的样子:
def find(x):
x = str(x)
count = 0
if str((10 - int(x[0]))) in x:
count = count + 1
x = x[1:]
find(x)
elif len(x) > 1:
x = x[1:]
find(x)
return count
我遇到的问题是,函数总是返回计数为1,因为我再次调用它进行递归,并且它将计数设置回0,而不是每次找到一对就将1添加到计数中。有人知道我怎么解决这个问题吗 可以使用单独的函数声明
count
,然后调用find()
,也可以将count
设置为全局变量。我认为第一种方法更可取
def get_count(x):
count = 0
find(str(x))
return count
或者类似的。此外,如果使用该方法,请确保从原始的
find
函数中删除count=0
,一个可能的解决方案是简化,例如根本不使用递归。例如,请参见以下尝试:
def find(x):
x = str(x)
count = 0
for i in range(len(x)-1):
if str((10-int(x[i]))) in x[i+1:]:
count += 1
return count
现在,您的代码没有使用递归
find
调用的返回值;它只是在调用find(x)
。这将解决您的问题:
def find(x):
x = str(x)
count = 0
if str((10 - int(x[0]))) in x:
# count = count + 1
x = x[1:]
count = 1 + find(x)
elif len(x) > 1:
x = x[1:]
count = find(x)
return count
全局变量通常是。是的,这就是为什么我说第一种方法更可取的原因。那么
555
呢?你会把(5,5)
计算为一对还是三对?也许ctr={int(d):c代表d,c在计数器(x)中。items()}
和返回和(ctr[i]*ctr.get(k-i,0)代表ctr中的i)//2
代表O(N)
?谢谢你,但我正试图通过这些实践问题来练习递归,谢谢你的帮助!太好了,非常感谢!