python实现递归实例代码

时间:2026-02-13 12:47:40

1、def great(n):

    if n == 1:

        return 1

    return n + great(n-1)

a = great(5)

print(a)

python实现递归实例代码

2、# 代码运行过程如下:

"""great(5)

5 + great(4)

5 + 4 + great(3)

5 + 4 + 3 + great(2)

5 + 4 + 3 + 2 + great(1)

5 + 4 + 3 + 2 + 1

"""

python实现递归实例代码

3、或者如下:

python实现递归实例代码

4、递归思想(条件):

"""1, 假设功能已经实现

2, 要有退出条件

"""

python实现递归实例代码

5、递归的功能类似于循环的:

def add_fn(n):

    res = 0

    for i in range(1, n+1):

        res += i

    return res

print(add_fn(5))

python实现递归实例代码

6、     递归虽然实现某些功能很简单,但是确实极为耗费内存资源,所以能用循环解决的问题尽量用循环,某些特殊的问题才可能要用递归解决。

© 2026 智德知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com