python - 如何使用递归查找加到 10 的数字
问题描述
我正在尝试编写一个函数,该函数将 int 作为参数并找到其中的数字对数加到 10。
例如,7645238 有 3 对,因为:7 + 3 = 10、6 + 4 = 10 和 2 + 8 = 10。
我必须递归地执行此操作,并且我已经完成了大部分代码,我只是有一个小问题。我在递归函数中使用了循环和计数器变量,但是每次函数循环时计数器变量都会重置。因此,如果一个数字有超过一对加到 10,计数器将始终只返回 1。
这是我在python中的代码:
def findPairs(num):
count = 0
num = str(num)
# base case if length of num is 1
if len(num) == 1:
return 0
# loops through the rest of the number looking for pairs
else:
for n in num[1:]:
if int(num[0]) + int(n) == 10:
count = count + 1
findPairs(num[1:])
return count
任何帮助将不胜感激!
解决方案
我认为问题出在返回代码中,您应该返回当前整数的计数器 + 递归计数器总和,所以这段代码可能会解决问题:
def findPairs(num):
count = 0
num = str(num)
# base case if length of num is 1
if len(num) == 1:
return 0
# loops through the rest of the number looking for pairs
for n in num[1:]:
if int(num[0]) + int(n) == 10:
count = count + 1
return count + findPairs(num[1:])
推荐阅读
- reactjs - 如何使用数据库内容填充 reactjs 表单?
- python - 如何在 Python 中重定向 os.system() 输出?
- typescript - Rxjs:fromPromise 和 toPromise 操作是否昂贵?
- permissions - 池 - 多处理 - [Errno 13] 权限被拒绝
- android - 疯狂的 Android Studio 内存使用
- snowflake-cloud-data-platform - 可以通过从另一列复制数据类型来创建表列吗?(例如 Oracle 中的 %type)
- python - Python dict.get 返回 0 评估为 false
- python - 从 scipy.interpolate 导入 RegularGridInterpolator 时出错
- sql - SQL:使用临时表和一列的 JOIN 问题
- c# - System.Net.WebException:“底层连接已关闭:接收时发生意外错误。”