首页 > 解决方案 > 分析递归算法

问题描述

我试图找出这个算法接受 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

标签: algorithmrecursion

解决方案


展开,它看起来像这样:

sum_func(4321)
= 1 + sum_func(432)
= 1 + 2 + sum_func(43)
= 1 + 2 + 3 + sum_func(4)
= 1 + 2 + 3 + 4

推荐阅读