十一、函数的递归

  定义:函数内部可以调用其他函数,如果一个函数在内部调用本身,则称为该函数为递归函数。

例1:死循环

import time
def calc(n):
    time.sleep(2)#两秒出一个数
    print(n)
    calc(n)
calc(10)

例2:让数字10不断的除2,将整数列举出来

def calc(n):
    print(n)
    if int(n/2)==0:
        return n
    res=calc(int(n/2))
    return res
calc(10)
'''
运行结果:
10
5
2
1
'''

例3:问路程序

import time
#首先定义一个路人列表
person_list=['lyl','zx','zjf','zh','lll']
#开始问路
def ask_way(person_list):
    print("*"*80)
    #明确终止条件(1、都不知道;2、zh知道路)
    if len(person_list)==0:
        return "都不知道,爱咋咋地"
    person=person_list.pop(0)#在列表中将被问路人一一弹出
    #zh知道路
    if person == 'zh':
        return "%s说:在有极光的地方" %person

    #代码修饰部分
    print("Where 麻将馆")
    print("%s说:不到,下一个!!,请去问%s" %(person,person_list))
    time.sleep(3)#时间
    res=ask_way(person_list)
    return res
res=ask_way(person_list)
print(res)

运行结果:

递归特性:
1.必须有一个明确的结束条件
2.每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3.递归效率不高;递归层次过多会导致栈澄出(在计算机中,函数调用是通过楼(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于找的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出>

原文地址:https://www.cnblogs.com/hzzhbest/p/14804994.html