使用递归得到数字的总和

时间:2019-04-12 03:27:19

标签: python python-3.x

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

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

<h2>Small content</h2>
<div class="container">
  <div class="item">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRu-3yBSd2b6JCOMcGVSOFf8X49QB3Ik-OI87gKEMwWLrdJxP5qOErmZQ"></div>
  <div class="item">
    <div class="content">some text here some text here some text here </div>
  </div>
</div>
<br/>
<h2>Large Content</h2>
<div class="container">
  <div class="item">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRu-3yBSd2b6JCOMcGVSOFf8X49QB3Ik-OI87gKEMwWLrdJxP5qOErmZQ"></div>
  <div class="item">
    <div class="content">some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here </div>
  </div>
</div>

输出:

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()

1 个答案:

答案 0 :(得分:1)

您不应迭代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