递归:为什么函数返回一个数字的阶乘而不是返回1?

Shr*_*kar 0 python algorithm recursion data-structures

def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n-1)


def rec():
    print fact(5)

rec()
Run Code Online (Sandbox Code Playgroud)

[来自新手的问题]

Python脚本.

这个问题在很长一段时间内仍然存在,让我解释一下到目前为止我对递归的理解.

rec()函数中,我再调用了一个函数fact(5),现在该过程转到了fact(n)函数.

函数调用自身直到基本情况.

在其他部分:

5*事实(4)

5*4*事实(3)

5*4*3*事实(2)

5*4*3*2*事实(1)

现在n的值变为0,并返回1

我的问题是,为什么事实(n)函数返回120而不是1.

def check(x):
    if x == 1:
        return 10
    else:
       return 20

print check(1) // Prints 10
print check(3) // Prints 20
Run Code Online (Sandbox Code Playgroud)

我希望你理解我的问题.

谢谢.

fre*_*ish 6

以下fact(5)是评估时堆栈的样子:

fact(5) = 5 * fact(4)
  fact(4) = 4 * fact(3)         
    fact(3) = 3 * fact(2)
      fact(2) = 2 * fact(1)
        fact(1) = 1 * fact(0)
          fact(0) = 1
          # no more recursive calls, unwind the stack
        fact(1) = 1 * 1 = 1
      fact(2) = 2 * 1 = 2
    fact(3) = 3 * 2 = 6
  fact(4) = 4 * 6 = 24
fact(5) = 5 * 24 = 120
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.每个缩进都是fact(N)返回的.