python入门第十三天__递归函数

实现一个阶乘fact():

def fact(n):
    ret=1
    for i in range(1,n+1):
        ret=ret*i
    return ret


print(fact(8))

结果:

$ python3 digui.py
40320

实现一个阶乘fact():

Python 3.6.5 (default, Apr  1 2018, 05:46:30) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def fact(n):
...     if n==1:
...             return 1
...     return n*fact(n-1)
... 
>>> fact(4)
24
>>> fact(8)
40320
>>> 

上面就是一个递归函数。

如果我们计算fact(5),可以根据函数定义看到计算过程如下:

===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。

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

>>> fact(1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in fact
  File "<stdin>", line 4, in fact
  File "<stdin>", line 4, in fact
  [Previous line repeated 994 more times]
  File "<stdin>", line 2, in fact
RecursionError: maximum recursion depth exceeded in comparison
>>> 
>>> fact(897564231)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in fact
  File "<stdin>", line 4, in fact
  File "<stdin>", line 4, in fact
  [Previous line repeated 994 more times]
  File "<stdin>", line 2, in fact
RecursionError: maximum recursion depth exceeded in comparison

 斐波那契数列:

def f(n):
    before=0
    after=1
    if n==1:
        return 0
    if n==2:
        return 1
    for i in range(0,n-2):
        before,after= after,after+before
    return after

for i in range(1,9):
    print(f(i))

 递归实现:

def f(n):
    if n==1:
        return 0
    if n==2:
        return 1    
    return f(n-1)+f(n-2)
 
for i in range(1,5000):
    print(f(i))
原文地址:https://www.cnblogs.com/Mengchangxin/p/9224925.html