递归函数

在函数内部可以调用其他函数,如果他调用自己,这就叫递归函数.

如果我们计算N!的阶乘

定义一个fact()函数

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

计算fact(3),程序的执行过程是

=> fact(3)
=> 3* fact(2)
=> 3* (2 * fact(1))
=> 3 * (2 * 1))
=>3*2
=>6

递归函数写起来简单代码少,和循环比起来B格高

但是使用递归函数要防止栈溢出,在计算机中函数的调用时通过栈(stack)这种结构调用的,每当进入一个函数调用就会增加一层栈帧,所以层数不能太多,否则会报一个

RuntimeError: maximum recursion depth exceeded in comparison

所以就有了尾递归来解决这个问题,也就是在进入下一个函数调用前,先将上一个函数的结果算好带过去,也就是return 语句不包含任何表达式

def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)
原文地址:https://www.cnblogs.com/hanshuai0921/p/7053957.html