更好的阅读体验

Currying

We can transform multiple-argument functions into a chain of single-argument, higher order functions. For example, we can write a function f(x, y) as a different function g(x)(y). This is known as currying.

For example, to convert the function add(x, y) into its curried form:

def curry_add(x):def add2(y):return x + yreturn add2

Calling curry_add(1) returns a new function which only performs the addition once the returned function is called with the second addend.

>>> add_one = curry_add(1)
>>> add_one(2)
3
>>> add_one(4)
5

Refer to the textbook for more details about currying.

What Would Python Display?

Important: For all WWPD questions, type Function if you believe the answer is <function...>, Error if it errors, and Nothing if nothing is displayed.

Q1: WWPD: Lambda the Free

Use Ok to test your knowledge with the following “What Would Python Display?” questions:

python3 ok -q lambda -u✂️

As a reminder, the following two lines of code will not display anything in the Python interpreter when executed:

>>> x = None
>>> x
>>> lambda x: x  # A lambda expression with one parameter x______
>>> a = lambda x: x  # Assigning the lambda function to the name a
>>> a(5)______
>>> (lambda: 3)()  # Using a lambda expression as an operator in a call exp.______
>>> b = lambda x: lambda: x  # Lambdas can return other lambdas!
>>> c = b(88)
>>> c______
>>> c()______
>>> d = lambda f: f(4)  # They can have functions as arguments as well.
>>> def square(x):
...     return x * x
>>> d(square)______
>>> x = None # remember to review the rules of WWPD given above!
>>> x
>>> lambda x: x______
>>> z = 3
>>> e = lambda x: lambda y: lambda: x + y + z
>>> e(0)(1)()______
>>> f = lambda z: x + z
>>> f(3)______
>>> 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?______
>>> higher_order_lambda(g)(2)______
>>> call_thrice = lambda f: lambda x: f(f(f(x)))
>>> call_thrice(lambda y: y + 1)(0)______
>>> print_lambda = lambda z: print(z)  # When is the return expression of a lambda expression executed?
>>> print_lambda______
>>> one_thousand = print_lambda(1000)______
>>> one_thousand______

Q2: WWPD: Higher Order Functions

Use Ok to test your knowledge with the following “What Would Python Display?” questions:

python3 ok -q hof-wwpd -u✂️
>>> 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______
>>> stewart(61)______
>>> stewart(-4)______
>>> def cake():
...    print('beets')
...    def pie():
...        print('sweets')
...        return 'cake'
...    return pie
>>> chocolate = cake()______
>>> chocolate______
>>> chocolate()______
>>> more_chocolate, more_cake = chocolate(), cake______
>>> more_chocolate______
>>> def snake(x, y):
...    if cake == more_cake:
...        return chocolate
...    else:
...        return x + y
>>> snake(10, 20)______
>>> snake(10, 20)()______
>>> cake = 'cake'
>>> snake(10, 20)______

Parsons Problems

To work on these problems, open the Parsons editor:

python3 parsons

Q3: A Hop, a Skip, and a Jump

Complete hop, which implements a curried version of the function f(x, y) = y.

def hop():"""Calling hop returns a curried version of the function f(x, y) = y.>>> hop()(3)(2) # .Case 12>>> hop()(3)(7) # .Case 27>>> hop()(4)(7) # .Case 37""""*** YOUR CODE HERE ***"return lambda x: lambda y: y

Q4: Digit Index Factory

Complete the function digit_index_factory, which takes in two integers k and num as input and returns a function. The returned function takes no arguments, and outputs the offset between k and the rightmost digit of num. The offset between two numbers is defined to be the number of steps between the two numbers. For example, in 25, there is an offset of 1 between 2 and 5.

Note that 0 is considered to have no digits (not even 0).

def digit_index_factory(num, k):"""Returns a function that takes no arguments, and outputs the offsetbetween k and the rightmost digit of num. If k is not in num, thenthe returned function returns -1. Note that 0 is considered tocontain no digits (not even 0).>>> digit_index_factory(34567, 4)() # .Case 13>>> digit_index_factory(30001, 0)() # .Case 21>>> digit_index_factory(999, 1)() # .Case 3-1>>> digit_index_factory(1234, 0)() # .Case 4-1""""*** YOUR CODE HERE ***"def digit_index_factory(num, k):1index = 0while num:if num % 10 == k:return lambda: indexindex += 1num //= 107return lambda: -1

Coding Practice

Q5: Lambdas and Currying

Write a function lambda_curry2 that will curry any two argument function using lambdas.

Your solution to this problem should fit entirely on the return line. You can try first writing a solution without the restriction, and then rewriting it into one line after.

If the syntax check isn’t passing: Make sure you’ve removed the line containing "***YOUR CODE HERE***" so that it doesn’t get treated as part of the function for the syntax check.

def lambda_curry2(func):"""Returns a Curried version of a two-argument function FUNC.>>> from operator import add, mul, mod>>> curried_add = lambda_curry2(add)>>> add_three = curried_add(3)>>> add_three(5)8>>> curried_mul = lambda_curry2(mul)>>> mul_5 = curried_mul(5)>>> mul_5(42)210>>> lambda_curry2(mod)(123)(10)3""""*** YOUR CODE HERE ***"return lambda x: lambda y: func(x, y)

Use Ok to test your code:

python3 ok -q lambda_curry2✂️

Q6: Count van Count

Consider the following implementations of count_factors and count_primes:

def count_factors(n):"""Return the number of positive factors that n has.>>> count_factors(6)4   # 1, 2, 3, 6>>> count_factors(4)3   # 1, 2, 4"""i = 1count = 0while i <= n:if n % i == 0:count += 1i += 1return countdef count_primes(n):"""Return the number of prime numbers up to and including n.>>> count_primes(6)3   # 2, 3, 5>>> count_primes(13)6   # 2, 3, 5, 7, 11, 13"""i = 1count = 0while i <= n:if is_prime(i):count += 1i += 1return countdef is_prime(n):return count_factors(n) == 2 # only factors are 1 and n

The implementations look quite similar! Generalize this logic by writing a function count_cond, which takes in a two-argument predicate function condition(n, i). count_cond returns a one-argument function that takes in n, which counts all the numbers from 1 to n that satisfy condition when called.

def count_cond(condition):"""Returns a function with one parameter N that counts all the numbers from1 to N that satisfy the two-argument predicate function Condition, wherethe first argument for Condition is N and the second argument is thenumber from 1 to N.>>> count_factors = count_cond(lambda n, i: n % i == 0)>>> count_factors(2)   # 1, 22>>> count_factors(4)   # 1, 2, 43>>> count_factors(12)  # 1, 2, 3, 4, 6, 126>>> is_prime = lambda n, i: count_factors(i) == 2>>> count_primes = count_cond(is_prime)>>> count_primes(2)    # 21>>> count_primes(3)    # 2, 32>>> count_primes(4)    # 2, 32>>> count_primes(5)    # 2, 3, 53>>> count_primes(20)   # 2, 3, 5, 7, 11, 13, 17, 198""""*** YOUR CODE HERE ***"def counter(n):i = 1cnt = 0while i <= n:if condition(n, i):cnt = cnt + 1i = i + 1return cntreturn counter

Use Ok to test your code:

python3 ok -q count_cond✂️

Submit

Make sure to submit this assignment by running:

python3 ok --submit

Optional Questions

Q7: Composite Identity Function

Write a function that takes in two single-argument functions, f and g, and returns another function that has a single parameter x. The returned function should return True if f(g(x)) is equal to g(f(x)). You can assume the output of g(x) is a valid input for f and vice versa. Try to use the composer function defined below for more HOF practice.

def composer(f, g):"""Return the composition function which given x, computes f(g(x)).>>> add_one = lambda x: x + 1        # adds one to x>>> square = lambda x: x**2>>> a1 = composer(square, add_one)   # (x + 1)^2>>> a1(4)25>>> mul_three = lambda x: x * 3      # multiplies 3 to x>>> a2 = composer(mul_three, a1)    # ((x + 1)^2) * 3>>> a2(4)75>>> a2(5)108"""return lambda x: f(g(x))def composite_identity(f, g):"""Return a function with one parameter x that returns True if f(g(x)) isequal to g(f(x)). You can assume the result of g(x) is a valid input for fand vice versa.>>> add_one = lambda x: x + 1        # adds one to x>>> square = lambda x: x**2>>> b1 = composite_identity(square, add_one)>>> b1(0)                            # (0 + 1)^2 == 0^2 + 1True>>> b1(4)                            # (4 + 1)^2 != 4^2 + 1False""""*** YOUR CODE HERE ***"def identity(x):return composer(f, g)(x) == composer(g, f)(x)return identity

Use Ok to test your code:

python3 ok -q composite_identity✂️

Q8: I Heard You Liked Functions…

Define a function cycle that takes in three functions f1, f2, f3, as arguments. cycle will return another function that should take in an integer argument n and return another function. That final function should take in an argument x and cycle through applying f1, f2, and f3 to x, depending on what n was. Here’s what the final function should do to x for a few values of n:

  • n = 0, return x
  • n = 1, apply f1 to x, or return f1(x)
  • n = 2, apply f1 to x and then f2 to the result of that, or return f2(f1(x))
  • n = 3, apply f1 to x, f2 to the result of applying f1, and then f3 to the result of applying f2, or f3(f2(f1(x)))
  • n = 4, start the cycle again applying f1, then f2, then f3, then f1 again, or f1(f3(f2(f1(x))))
  • And so forth.

Hint: most of the work goes inside the most nested function.

def cycle(f1, f2, f3):"""Returns a function that is itself a higher-order function.>>> def add1(x):...     return x + 1>>> def times2(x):...     return x * 2>>> def add3(x):...     return x + 3>>> my_cycle = cycle(add1, times2, add3)>>> identity = my_cycle(0)>>> identity(5)5>>> add_one_then_double = my_cycle(2)>>> add_one_then_double(1)4>>> do_all_functions = my_cycle(3)>>> do_all_functions(2)9>>> do_more_than_a_cycle = my_cycle(4)>>> do_more_than_a_cycle(2)10>>> do_two_cycles = my_cycle(6)>>> do_two_cycles(1)19""""*** YOUR CODE HERE ***"def ref_fn(n):def ret(x):if n == 0:return xreturn cycle(f2, f3, f1)(n - 1)(f1(x))return retreturn ref_fn

Use Ok to test your code:

python3 ok -q cycle

CS61A Lab 2相关推荐

  1. CS61A Lab 7

    更好的阅读体验 Lab 7: Linked Lists, Trees / Tree Mutation lab07.zip What Would Python Display? Q1: WWPD: Li ...

  2. CS61A Lab 8

    更好的阅读体验 Lab 8: Midterm Review lab08.zip Due by 11:59pm on Wednesday, March 16. Starter Files Downloa ...

  3. CS61A Lab 10

    更好的阅读体验 Lab 10: Scheme lab10.zip Due by 11:59pm on Wednesday, March 30. Starter Files Download lab10 ...

  4. CS61A Lab 12

    更好的阅读体验 Lab 12: Scheme Data Abstraction lab12.zip Due by 11:59pm on Wednesday, April 13. Starter Fil ...

  5. CS61A Lab 4

    更好的阅读体验 Lab 4: Recursion, Tree Recursion lab04.zip What Would Python Do? Q1: Squared Virahanka Fibon ...

  6. CS61A Lab 14

    更好的阅读体验 Lab 14 Solutions lab14.zip Solution Files This lab has many files. Remember to write in lab1 ...

  7. CS61A Lab 6

    更好的阅读体验 Lab 6: Object-Oriented Programming lab06.zip What Would Python Do? These questions use inher ...

  8. CS61A Lab 1

    更好的阅读体验 Lab 1: Variables & Functions, Control lab01.zip What Would Python Display? (WWPD) Q1: WW ...

  9. CS61A Lab 11

    更好的阅读体验 Lab 11: Interpreters lab11.zip Due by 11:59pm on Wednesday, April 6. Starter Files Download ...

  10. CS61A Lab 13

    更好的阅读体验 Lab 13 Solutions lab13.zip Solution Files Topics Consult this section if you need a refreshe ...

最新文章

  1. python语音翻译软件下载_python软件翻译
  2. 不插电的计算机科学读心术,科学“读心术”,当脑电波扫描图遇到人工智能
  3. Java-二叉树算法
  4. Redis开发运维实践问题处理只内存检查
  5. JS基础语法(04)-逗号运算符
  6. Python查找指定文件
  7. USACO详细介绍 全球中小学生均可参加
  8. 我的内核学习笔记16:海思Hi3516平台PWM使用记录
  9. 第五章 处理器拦截器详解
  10. [spark]Spark2.4.6用put写入写入Hbase1.3.1
  11. WPF学习:3.Border Brush
  12. smbus使用 树莓派_Linux控制I2C/SMBus设备
  13. 小米平板2wifi驱动下载_小米WiFi驱动官方下载_Xiaomi小米随身WiFi驱动官方最新版下载-华军软件园...
  14. win7 计算机打不开搜狗,Win7电脑搜狗输入法不见了如何解决?
  15. 强制推广鸿蒙系统,鸿蒙系统凭实力占市场,无需通过禁止安卓系统来推广
  16. ie8对fixed的支持较差
  17. 从2018年全球半导体数据中看物联网芯片产业现状
  18. python if else 嵌套格式_python中if嵌套命令实例讲解
  19. 倡导国稻种芯·中国水稻节 万祥军:农民丰收节金秋消费季
  20. python安装PyQt5_stylesheets

热门文章

  1. Android多人视频聊天应用的开发(一)快速集成
  2. Java历史、现状和各版本技术更迭总结
  3. RK3588平台开发系列讲解(PWM篇)PWM及backlight的使用方法
  4. 李开复给中国大学生的第六封信—选择的智慧
  5. iphone测试oled的软件,干货 |西努妙解 iPhoneX OLED全面屏的检测方法
  6. 小菜鸟之oracle数据字典
  7. **潘老师 领导力\管理效能提升专家**
  8. 【教你赚钱】5分钟成为副业致富的独立开发者
  9. 奇虎360 2015校园招聘笔试编程题
  10. 回溯法采用的搜索策略_五大常用算法之四:回溯法