黑猴子的家:python 递归函数

1、初始递归函数

递归函数定义

在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数

code

def calc(n):
    print(n)
    if int(n / 2) == 0:
        return n
    return calc(int(n / 2))

calc(10)

打印

10
5
2
1

递归特性

(1)必须有一个明确的结束条件

(2)每次进入更深一层递归时,问题规模相比上次递归都应有所减少

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

2、递归函数实际应用案例,二分查找

code

#author = "黑猴子的家"

data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]


def binary_search(dataset, find_num):
    print(dataset)

    if len(dataset) > 1:
        mid = int(len(dataset) / 2)
        if dataset[mid] == find_num:  # find it
            print("找到数字", dataset[mid])
        elif dataset[mid] > find_num:  # 找的数在mid左面
            print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])
            return binary_search(dataset[0:mid], find_num)
        else:  # 找的数在mid右面
            print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])
            return binary_search(dataset[mid + 1:], find_num)
    else:
        if dataset[0] == find_num:  # find it
            print("找到数字啦", dataset[0])
        else:
            print("没的分了,要找的数字[%s]不在列表里" % find_num)


binary_search(data,32)

打印

[1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
找的数在mid[18]右面
[20, 21, 22, 23, 30, 32, 33, 35]
找的数在mid[30]右面
[32, 33, 35]
找的数在mid[33]左面
[32]
找到数字啦 32

3、递归函数练习

#超过最大递归数 999层, 报异常
def calc(n):
     print(n)
     return calc(n+1)

calc(0)


#递归
print("-------------递归打印1000-------------")
def calc2(n):
    print(n)
    n = n + 1
    if n < 100:
        return calc2(n)

calc2(0)

#打印1000
# for 循环能成功  递归不行
print("---------for----------")
for i in range(1000):
    print(i)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值