Python - 创建整数列表并使用递归求和

0 投票
3 回答
831 浏览
提问于 2025-04-18 04:30

我正在尝试创建一个程序,它可以接收用户输入的整数,然后生成一个列表,最后通过递归的方式将列表中的数字相加。问题是,当我输入6时,结果却是15,而正确的答案应该是(0+1+2+3+4+5+6) = 21。为什么计算结果会出错呢?我觉得可能是索引的问题,因为如果不算6,结果确实是15。

#Program which accepts a number from the user
#take the numbers 0 to the number input 
#and gives a total of the numbers

def main():
#Get the number from the user to define upper end of range
    num = int(input('Enter a non-negative integer: '))

#Create the list of numbers
numbers = list(range(0,num, 1))

#Get the sum of the list of numbers
my_sum = range_sum(numbers, 0, - 1)

#Display the total
print('The sum of 0 to', num, 'is: ', my_sum)

def range_sum(num_list, start, end):
if start < end:
    return 0
else:
    return sum(num_list)
#call the main function
main() 

3 个回答

0

代码里没有递归调用。你使用的是Python里自带的sum函数。

0

这是一个相对简单的函数,可以通过递归的方式来实现:

def recursive(n):
    if n == 1:
        return n
    return n + recursive(n - 1)

或者通过迭代的方式来实现:

def iterative(n):
    return sum(range(n + 1)) # note n + 1 - range excludes the stop argument

这两种方式是等价的:

def iterative_longhand(n):
    total = 0
    for i in range(n + 1):
        total += i
    return total

如果需要使用列表的话:

def recursive_list_sum(nums):
    if nums:
        return nums[0] + recursive_list_sum(nums[1:])
    return 0

recursive_list_sum(list(range(n + 1)))

你的标题提到“使用递归”,但你的函数没有调用自己。你并没有使用递归来构建列表,也没有用递归来计算它的内容总和。这个函数:

def range_sum(num_list, start, end):
    if start < end:
        return 0
    else:
        return sum(num_list)

调用方式是:

range_sum(numbers, 0, - 1)

实际上就是 sum(num_list),因为 start > end。不太清楚你想要达到什么效果——如果应该使用递归的话,函数内部应该有对 range_sum 的调用。

0

使用尾递归:

def range_sum(nums, sum=0):
    if not nums:
        return sum
    sum += nums.pop()
    return range_sum(nums, sum)

撰写回答