python - 使用递归获取数字的总和
问题描述
设计一个接受整数参数并返回从 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
解决方案
您不应该遍历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
推荐阅读
- php - PHP 大型视频文件流式传输
- javascript - 将 CSS 结构解析为对象
- java - 如何解决数据库登录问题?
- asynchronous - SwiftUI 或组合时钟/定时器事件
- database - 如何处理在 Spring 中返回大量项目列表?
- javascript - 根据数组元素的总和对数组中的元素进行排序
- sqlite - 如何对部分填充的 sqlite 页面进行碎片整理/合并以回收空间?
- jquery - Odoo 13:如何在 Odoo 中进行 ajax 调用?
- java - 如何在 TextView 中显示左引号(底部对齐)?
- javascript - 当组件安装在 React 中时如何刷新照片链接引用?