首页 > 解决方案 > 使用递归获取数字的总和

问题描述

设计一个接受整数参数并返回从 1 到作为参数传递的数字的所有整数之和的函数。

它运行并显示我输入的数字。然后我将这些值存储在列表中。不会在列表中添加值

def main():

    #local var
    number = 0
    num_list = []

    #input number from user
    number = int(input('Enter number: '))

    print_num(number)
    print('The total value of the list is: ', sum_list(num_list))

def print_num(n):
    num_list = []
    if n > 1:
        print_num(n - 1)
        num_list.append(n)

        print(n, sep =' ')
    return num_list

def sum_list(num_list): 
    for i in range(len(num_list)):  
        if len(num_list) == 0:
             return num_list[0]
        else:
            return num_list[0] + sum_list(num_list[1:])


main()

输出:

Enter number: 10
2
3
4
5
6
7
8
9
10
The total value of the list is:  None

标签: pythonpython-3.x

解决方案


您不应该遍历num_list. 相反,返回第一项加上递归调用的返回值与其余项的总和,直到列表为空,此时返回 0:

def sum_list(num_list):
    if not num_list:
        return 0
    return num_list[0] + sum_list(num_list[1:])

这样sum_list([1, 5, 4, 2])返回:12


推荐阅读