algorithm - 分析递归算法
问题描述
我试图找出这个算法接受 an 的输入int
并且应该返回int
.
# Input -> 4321
# output -> 10 (4+3+2+1)
def sum_func(n):
# Base case
if len(str(n)) == 1:
return n
# Recursion
else:
return n%10 + sum_func(n/10)
当试图分解这个算法时,这就是我想出的
1st loop -> 1 + 432 = 433
2nd loop -> 2 + 43 = 45
3rd loop -> 3 + 4 = 7
4th loop -> 4 + 4 = 8
它是如何得出结果的10
?
解决方案
展开,它看起来像这样:
sum_func(4321)
= 1 + sum_func(432)
= 1 + 2 + sum_func(43)
= 1 + 2 + 3 + sum_func(4)
= 1 + 2 + 3 + 4
推荐阅读
- macos - 在mac中发生注销时如何以编程方式运行任务
- node.js - 用节点反应 SSR - ReferenceError:文档未定义
- c++ - 如何在 C++ 中获取 Antlr 4 规则名称?
- kubernetes - k8s pod经常保持OOMkilled
- php - SQLSTATE [42S22]:未找到列:1054 '字段列表'中的未知列 'id'
- azure-devops - Azure DevOps REST Api 标签调用(存储库 > 标签)
- java - Thymeleaf 条件类附加不起作用
- node.js - 为什么我收到此错误:npm ERR!代码生命周期
- python - SQL/Hive 查询以计算特定值每天的行数
- scala - 使用 spark 数据框读取 kafka 主题