码迷,mamicode.com
首页 > 编程语言 > 详细

06python 中的递归函数(python函数)

时间:2019-01-08 19:24:12      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:not   python函数   深度   lob   ret   函数   oba   turn   超过   

什么递归?

在函数内部自己调用自己就叫做递归(递归的最大深度不要超过1000次)

递归代码

n = 0


def story():
    global n
    n += 1
    print(n)
    story()


story()
>>>1
...
998

 递归函数与斐波那契

def fib(n):
    """
    This is Fibonacci by Recursion.
    """
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

 

 求斐波那契函数的第n个值

meno = {0:0, 1:1}    #初始化

def fib(n):
    if not n in meno:    #如果不在初始化范围内
        meno[n] = fib(n-1) + fib(n-2)
    return meno[n]


f = fib(10)
print f

>>>55

 

 递归与阶乘

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

 

06python 中的递归函数(python函数)

标签:not   python函数   深度   lob   ret   函数   oba   turn   超过   

原文地址:https://www.cnblogs.com/pontoon/p/10240445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!