CS 61A 2020 fall Lab 2: Higher-Order Functions, Lambda Expressions

这篇博客探讨了Python中的Lambda函数和高阶函数的概念。内容包括Q1到Q5的问题,涉及如何使用Lambda表达式实现计数功能、创建加法器,以及深入理解函数对象和环境图。Q5中解释了函数对象的内在名称、作用域和变量绑定。最后,文章挑战读者定义一个函数,该函数接受三个函数作为参数并返回一个能周期性应用这些函数的复合函数。
摘要由CSDN通过智能技术生成

Q1: WWPD: Lambda the Free

>>> lambda x: x  # A lambda expression with one parameter x

<function <lambda> at ...>
______

>>> a = lambda x: x  # Assigning the lambda function to the name a
>>> a(5)

5
______

>>> (lambda: 3)()  # Using a lambda expression as an operator in a call exp.

3
______

>>> b = lambda x: lambda: x  # Lambdas can return other lambdas!
>>> c = b(88)
>>> c

<function <lambda> at ...>
______

>>> c()

88
______

>>> d = lambda f: f(4)  # They can have functions as arguments as well.
>>> def square(x):
...     return x * x
>>> d(square)

16
______
>>> x = None # remember to review the rules of WWPD given above!
>>> x
>>> lambda x: x


None
______
>>> z = 3
>>> e = lambda x: lambda y: lambda: x + y + z
>>> e(0)(1)()

4
______

>>> f = lambda z: x + z
>>> f(3)

NameError: name 'x' is not defined
______
>>> higher_order_lambda = lambda f: lambda x: f(x)
>>> g = lambda x: x * x
>>> higher_order_lambda(2)(g)  # Which argument belongs to which function call?

Error
______

>>> higher_order_lambda(g)(2)

4
______

>>> call_thrice = lambda f: lambda x: f(f(f(x)))
>>> call_thrice(lambda y: y + 1)(0)

3
______

>>> print_lambda = lambda z: print(z)  # When is the return expression of a lambda expression executed?
>>> print_lambda

-
______

>>> one_thousand = print_lambda(1000)

1000
______

>>> one_thousand

N/A
______

Q2: WWPD: Higher Order Functions

>>> def even(f):
...     def odd(x):
...         if x < 0:
...             return f(-x)
...         return f(x)
...     return odd
>>> steven = lambda x: x
>>> stewart = even(steven)
>>> stewart

None
______

>>> stewart(61)

None
______

>>> stewart(-4)

None
______
>>> def cake():
...    print('beets')
...    def pie():
...        print('sweets')
...     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值