• CS61A pyhton高阶函数/lambda


    CS61A pyhton----高阶函数

    A function that either:

    • Takes another function as an argument
    • Returns a function as its result

    All other functions are considered first-order functions.

    可以直接将函数名当成参数传入函数

    def cube(k):
        return k ** 3
    
    def summation(n, term):
        """Sum the first N terms of a sequence.
        >>> summation(5, cube)
        225
        """
        total = 0
        k = 1
        while k <= n:
            total = total + term(k)
            k = k + 1
        return total

    可以在函数中直接定义函数,此时子函数的域绑定在母函数下

    人话:母函数中的变量子函数也可以用

    def f (x):
        def g (y):
            return x+y
        return g
    
    f (1)(2)
    # 3

    lambda

    lambda <parameters>: <expression>

    sq = lambda x : x * x
    # sq(3) 9

    条件表达式

    <consequent> if <predicate> else <alternative>

    lambda x: x if x > 0 else 0

    多环境

    环境指的是一系列的 frame

    当一个name被提及时,python会找当前环境下最近的frame

    frame之间是调用的关系,或者父子关系

    curry化

    把一个带多参数的函数改成单参数的高阶函数

    def curry2(f):
        def g(x):
            def h(y):
                return f(x, y)
            return h
        return g

    from operator import add
    
    make_adder = curry2(add)
    make_adder(2)(3)

    curry2 = lambda f: lambda x: lambda y: f(x, y)

    两种写法均可

  • 相关阅读:
    idea-----Intellij IDEA配置tomcat(非maven项目)
    idea-----idea的项目中output框出现乱码
    mysql on windows的安装
    maven配置
    安装tomcat8.5
    jdk11.0.2安装
    idea创建maven web项目
    Mac下使用sshpass让iterm2支持多ssh登录信息保存
    iterm 2快捷键
    java 8 Base64用法
  • 原文地址:https://www.cnblogs.com/liankewei/p/15935018.html
Copyright © 2020-2023  润新知