递归:看起来像相同的函数,但打印出不同的执行流程

Recursion: look like same function but print out different flow of execution

我试着打印出阶乘递归函数的执行流程。

def factorial(n):
    space=' '*(4*n)
    print(space,'factorial ',n)
    if n==0:
        print(space,'returning 1')
        return 1
    else:
        recurse=factorial(n-1)
        result=n*recurse
        print(space,'returning ', result)
        return n*recurse

使用 factorial(2) 结果将是正确的:

        factorial 2
    factorial 1
factorial 0
returning 1
    returning 1
        returning 2
2

但是当我不使用变量时 recurse=factorial(n-1):

def factorial(n):
    space=' '*(4*n)
    print(space,'factorial ',n)
    if n==0:
        print(space,'returning 1')
        return 1
    else:
        result=n*factorial(n-1)
        print(space,'returning ', result)
        return n*factorial(n-1)

然后使用 factorial(2) 打印出不同的流程:

             factorial  2
     factorial  1
 factorial  0
 returning 1
     returning  1
 factorial  0
 returning 1
         returning  2
     factorial  1
 factorial  0
 returning 1
     returning  1
 factorial  0
 returning 1
2

我的问题是:为什么执行流程不同[有和没有变量 recurse=factorial(n-1)]?

这是由于您的代码中调用了以下额外函数

def factorial(n):
    space=' '*(4*n)
    print(space,'factorial ',n)
    if n==0:
        print(space,'returning 1')
        return 1
    else:
        result=n*factorial(n-1)
        print(space,'returning ', result)
        return n*factorial(n-1)   # factorial(n-1) is called second time so that this function is executed once again

你可以按照下面的方式进行类似的执行

def factorial(n):
    space=' '*(4*n)
    print(space,'factorial ',n)
    if n==0:
        print(space,'returning 1')
        return 1
    else:
        result=n*factorial(n-1)
        print(space,'returning ', result)
        return result