zoukankan      html  css  js  c++  java
  • Day3-递归函数、高阶函数、匿名函数

    一、递归函数

    定义:函数内部可以调用其它函数,如果调用自身,就叫递归。

    递归特性:

    1.必须有结束条件退出:

    >>> def calc(n):
    ...     print(n)
    ...     return calc(n+1)
    ...
    >>> calc(0)
    0
    1
    ...
    998
    RecursionError: maximum recursion depth exceeded while calling a Python object
    
    分析:
    没有结束条件,超过最大递归次数999次后报错
    View Code

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

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

    def calc(n):
        print(n)
        if int(n/2) > 0 :   #int()返回整数
            return calc(int(n/2))
        print("-->",n)
    calc(10)
    
    执行结果:
    10
    5
    2
    1
    --> 1

    二、匿名函数

    匿名函数就是不需要显式的指定函数

     #这段代码
    def calc(n):
        return n**n
    print(calc(10))
     
    #换成匿名函数
    calc = lambda n:n**n
    print(calc(10))
    10000000000

    与其它函数配合使用,

    1 res = map(lambda x:x**2,[1,5,7,4,8])
    2 for i in res:
    3     print(i)
    4 输出
    5 1
    6 25
    7 49
    8 16
    9 64

    map函数用法:第一个参数接收一个函数名,第二个参数接收一个可迭代对象

     1 ls = [1,2,3]
     2 rs = map(str, ls)
     3 print rs
     4 执行结果:
     5 ['1', '2', '3']
     6 ---------------------------------
     7 lt = [1, 2, 3, 4, 5, 6]
     8 def add(num):
     9     return num + 1
    10  
    11 rs = map(add, lt)
    12 print rs 
    13 [2,3,4,5,6,7]
    View Code

    三、高阶函数

    变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

    1 def add(x,y,f):
    2     return f(x) + f(y)
    3 res = add(3,-6,abs)
    4 print(res)
    5 9
    View Code
  • 相关阅读:
    设计模式20-观察者模式
    设计模式19-备忘录模式
    设计模式18-中介者模式
    设计模式17-迭代器模式
    设计模式16-解释器模式
    Wireshark基本介绍和学习TCP三次握手
    Jmeter CSV 参数化/检查点/断言
    Jmeter运营活动并发测试—巧用集合点
    一个简单的性能测试
    Jmeter对HTTP请求压力测试、并发测试
  • 原文地址:https://www.cnblogs.com/wolfs685/p/6724106.html
Copyright © 2011-2022 走看看