简体   繁体   English

返回一个范围内所有奇数之和的递归函数

[英]Recursive function that returns sum of all odd numbers within a range

I've been trying to create a recursive function that, as the title says, returns the value of the sum of all the odd numbers included in that range.我一直在尝试创建一个递归函数,正如标题所说,它返回该范围内所有奇数之和的值。 I tried the following:我尝试了以下方法:

def addOdds(A,B):
    for i in range (A,B):
        if i % 2 == 0:
            return addOdds(A,B-1)
        elif i % 2 != 0:
            return (i+addOdds(A,B-1))

print(addOdds(2, 125))

with that input, my output should be 3968 but instead I'm getting None and if i print i i get 0. Any clues on what I'm doing wrong?使用该输入,我的输出应该是3968 ,但我得到的是 None,如果我打印i得到 0。关于我做错了什么的任何线索?

Since B decreases in recursion, there's no need for the for-loop.由于 B 递归减少,因此不需要 for 循环。 Then to ensure the recursion ends, you need to specify what to return when B becomes equal to A.然后为确保递归结束,您需要指定当 B 等于 A 时要返回的内容。

def addOdds(A,B):
    if A == B:
        return 0
    else:
        if B % 2 == 0:
            return addOdds(A, B-1)
        else:
            return B + addOdds(A, B-1)

print(addOdds(2, 125))
# 3968

Here's the python code to do this in a simple manner这是以简单的方式执行此操作的python代码

def addOdds(A, B, total):  #pass the range with 0 as total Ex: 1,5,0
    if (A <= B):
        if (A % 2 != 0):  #check if A is odd
            total += A    
        return(addOdds(A+1, B, total))   #pass the new range with total Ex: 2,5,1
       
    return total


ans = addOdds(2, 125, 0)

print(ans)


output:输出:

3968

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

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