函数和函数式编程: 递归(recursion)及其应用

一.递归定义

如果一个函数再定义中包含自身的引用,那么我们就说这个函数是递归的(或者称该函数为递归函数)。

代码示例:

# -*- coding:utf-8 -*-


def my_recursive():
    """
    最简单的递归函数
    """
    my_recursive()

在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出[1]。

在Python中,会因为自身设置的保护措施(限定递归的循环次数,该次数可更改)而不断抛出异常,最后抛出一个RecursionError: maximum recursion depth exceeded异常。

>>> def my_recursive():
...     my_recursive()
... 
>>> my_recursive()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in my_recursive
  File "", line 2, in my_recursive
  File "", line 2, in my_recursive
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
>>> 

二.尾部递归

 

 参考资料

[1]廖雪峰,递归函数:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756044276a15558a759ec43de8e30eb0ed169fb11000

 

 

 

 

 

你可能感兴趣的:(Python)