[2021 spring] CS61A Lab 2: Higher-Order Functions, Lambda Expressions

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结果

全部通过:

posted @ 2021-06-14 11:45  ikventure  阅读(1918)  评论(0编辑  收藏  举报