Python,将迭代函数转换为递归函数

Kri*_*lex 6 python recursion loops

我创建了一个迭代函数,输出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)
Run Code Online (Sandbox Code Playgroud)

如果我想要一个完全相同的递归函数,我该怎么想?

Meh*_*far 11

试试这个:

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

        if n:
            print(n)

bounce(4)
Run Code Online (Sandbox Code Playgroud)

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