简体   繁体   English

如何使用递归查找加到 10 的数字

[英]How to find numbers that add to 10 using recursion

I'm trying to write a function that takes an int as a parameter and finds the number of pairs of numbers within that add to 10.我正在尝试编写一个 function ,它以 int 作为参数并找到其中的数字对数加到 10。

For example, 7645238 has 3 pairs because: 7 + 3 = 10, 6 + 4 = 10, and 2 + 8 = 10.例如,7645238 有 3 对,因为:7 + 3 = 10、6 + 4 = 10 和 2 + 8 = 10。

I have to do this recursively and I have most of the code done, I just have a small problem.我必须递归地执行此操作,并且我已经完成了大部分代码,我只是有一个小问题。 I'm using a loop and counter variable in my recursive function, but the counter variable resets each time the function loops.我在递归 function 中使用了循环和计数器变量,但是每次 function 循环时计数器变量都会重置。 Thus, if a number has more than one pair that adds to 10, the counter will always only return 1.因此,如果一个数字有超过一对加到 10,计数器将始终只返回 1。

Here's my code in python:这是我在 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

Any help would be greatly appreciated!任何帮助将不胜感激!

I think the problem is in the returning code, you should return the counter for the current integer + the recursive counters sum, so probably this code will fix the problem:我认为问题出在返回代码中,您应该返回当前 integer 的计数器 + 递归计数器总和,所以这段代码可能会解决问题:

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:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM