递归函数和匿名函数

1. 递归函数

在函数内部,能够调用其余函数。若是一个函数在内部调用自身自己,这个函数就是递归函数。数据结构

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

calc(10)

输出:
10
5
2
1

递归特性:ide

  1. 必须有一个明确的结束条件函数

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

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

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

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("找的数在mid[%s]左面" % dataset[mid])
            return binary_search(dataset[0:mid], find_num)
        else:# 找的数在mid右面
            print("找的数在mid[%s]右面" % 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,66)

2. 匿名函数

匿名函数就是不须要显式的指定函数递归

#这段代码
def calc(n):
    return n**n
print(calc(10))

#换成匿名函数
calc = lambda n:n**n
print(calc(10))

匿名函数主要是和其它函数搭配使用,以下:it

res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)
相关文章
相关标签/搜索