lab02:https://inst.eecs.berkeley.edu/~cs61a/sp21/lab/lab02/#topics
快速回顧:
Lambda Expressions
Environment Diagrams
Assignment Statements
def Statements
Call expressions
Lambdas
必答題 required questions
what would python display
Q1: WWPD: Lambda the Free
python ok -q lambda -u --local
部分問題:
Q2: WWPD: Higher Order Functions
python ok -q hof-wwpd -u --local
Coding Practice
Q3: Lambdas and Currying
先考慮def定義,再用lambda重寫成一行。
def lambda_curry2(func):
def f(x):
def g(y):
return func(x, y)
return g
return f
def lambda_curry2(func):
return lambda x: lambda y: func(x, y)
Q4: Count van Count
觀察重復代碼,重構:
def count_cond(condition):
"""Returns a function with one parameter N that counts all the numbers from
1 to N that satisfy the two-argument predicate function Condition, where
the first argument for Condition is N and the second argument is the
number from 1 to N.
def g(n):
i = 1
count = 0
while i <= n:
if condition(n, i):
count += 1
i += 1
return count
return g
Environment Diagram Practice
There is no submission for this component. However, we still encourage you to do these problems on paper to develop familiarity with Environment Diagrams, which might appear in an alternate form on the exam.
Q5: Make Adder
Q6: Lambda the Environment Diagram
Submit
python ok --submit
Optional Questions
Q7: Composite Identity Function
比較f(g(x))和g(f(x))即可:python ok -q composite_identity --local
def composite_identity(f, g):
"""
Return a function with one parameter x that returns True if f(g(x)) is
equal to g(f(x)). You can assume the result of g(x) is a valid input for f
and vice versa.
return lambda x: compose1(f, g)(x) == compose1(g, f)(x)
Q8: I Heard You Liked Functions...
先定義特例,再取模循環使用compose1:
def cycle(f1, f2, f3):
def g(n):
if n == 0:
return lambda x: x
if n == 1:
return f1
tmp = f1
i = 2
while i <= n:
if i % 3 == 1:
tmp = compose1(f1, tmp)
elif i % 3 == 2:
tmp = compose1(f2, tmp)
else:
tmp = compose1(f3, tmp)
i += 1
return tmp
return g
ok autograde結果
全部通過: