阶乘的递归函数

时间:2019-12-07 20:38:23

标签: python-3.x

我无法理解下面提到的代码的最后一行的逻辑。该代码是递归函数,可为您提供数字的阶乘。每次(阶乘(n-1))返回什么?

def factorial(n): if n<=1: return 1 else: return n*factorial(n-1)

================================================ ==================

1 个答案:

答案 0 :(得分:1)

如果您正在计算某件事的阶乘

1 * 2 * ... * n

另一种表示方式是

n * (n-1) * (n-2) * ... * 1

或更简化

n * (n-1) * ((n-1)-1) * ... * 1

查看最后一点,您应该可以看到,如果数字为1,则答案为1。否则,它是n的数字乘以(n-1)阶乘的结果。

这正是此功能的作用。

def factorial(n): # declare the function
    if n<=1: 
        return 1 # if n is 1 or lower, the answer should be 1.
    else: 
        # otherwise, the answer is the result of n * (all these steps again for (n-1))
        return n*factorial(n-1) 

假设您给factorial(5)实际发生的情况是

factorial(5) = 5 * factorial(4) 
    = 5 * (4 * factorial(3))
    = 5 * (4 * (3 * factorial(2)))
    = 5 * (4 * (3 * (2 * factorial(1))))
    = 5 * (4 * (3 * (2 * 1)))
相关问题