首页 > 解决方案 > Python,将迭代函数变成递归函数

问题描述

我创建了一个迭代函数,它输出 4 3 2 1 0 1 2 3 4。

def bounce2(n):
    s = n
    for i in range(n):
        print(n)
        n = n-1

    if n <= 0:
        for i in range(s+1):
            print(-n)
            n = n-1
    return
bounce2(4)

如果我想要一个做同样事情的递归函数,我应该怎么想?

标签: pythonloopsrecursion

解决方案


尝试这个:

def bounce(n):
    if n >= 0:
        print(n)
        bounce(n - 1)

        if n:
            print(n)

bounce(4)

输出将是:4 3 2 1 0 1 2 3 4


推荐阅读