[英]get the sum of numbers using recursion
design a function that accept an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument.设计一个函数,它接受一个整数参数并返回从 1 到作为参数传递的数字的所有整数的总和。
it runs and displays the numbers up to what i entered.它运行并显示我输入的数字。 then i stored those values in list.
然后我将这些值存储在列表中。 won't add values in list
不会在列表中添加值
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()
output:输出:
Enter number: 10
2
3
4
5
6
7
8
9
10
The total value of the list is: None
You should not iterate through the length of num_list
.您不应遍历
num_list
的长度。 Instead, return the sum of the first item plus the returning value of the recursive call with the rest of the items, until the list is empty, at which point return 0:相反,返回第一个项加上递归调用的返回值与其余项的总和,直到列表为空,此时返回 0:
def sum_list(num_list):
if not num_list:
return 0
return num_list[0] + sum_list(num_list[1:])
so that sum_list([1, 5, 4, 2])
returns: 12
所以
sum_list([1, 5, 4, 2])
返回: 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.