[CS61A] Lecture 5&6&7. Environments & Design & Functions Examples & Homework 2: Higher Order Functions
[CS61A] Lecture 5&6&7. Environments & Design & Functions Examples & Homework 2: Higher Order Functions
Lecture
Lecture 5. Environments
环境是编程语言中的一大命题,每个变量、函数都拥有它们所属的环境,也被称为作用域。
作用域在高阶函数中起到重要的作用,高阶函数中的变量因为作用域起到了状态的表示作用,使得多次调用特定的函数能够返回不同的结果。
Lecture 6. Design
- 函数抽象是编程语言很重要的一部分;
- 函数应该拥有一个有意义的名称,虽然对功能没有任何影响,但当程序复杂度上升时,好的函数名是函数功能最好的注释;
- 一个用函数组成的音乐制作器,比较神奇。
Lecture 7. Functions Examples
介绍了几个函数的例子,用来温习之前的知识点,最后介绍了装饰器的概念与用法。
Homework
Homework 2: Higher Order Functions
Q1: Product
要求实现product函数,返回term(1) * ... * term(n)
。
product函数:
def product(n, term):
"""Return the product of the first n terms in a sequence.
n: a positive integer
term: a function that takes one argument to produce the term
>>> product(3, identity) # 1 * 2 * 3
6
>>> product(5, identity) # 1 * 2 * 3 * 4 * 5
120
>>> product(3, square) # 1^2 * 2^2 * 3^2
36
>>> product(5, square) # 1^2 * 2^2 * 3^2 * 4^2 * 5^2
14400
>>> product(3, increment) # (1+1) * (2+1) * (3+1)
24
>>> product(3, triple) # 1*3 * 2*3 * 3*3
162
"""
return reduce(mul, [term(i) for i in range(1, n+1)])
Q2: Accumulate
要求实现accumulate函数。
accumulate函数:
def accumulate(merger, start, n, term):
"""Return the result of merging the first n terms in a sequence and start.
The terms to be merged are term(1), term(2), ..., term(n). merger is a
two-argument commutative function.
>>> accumulate(add, 0, 5, identity) # 0 + 1 + 2 + 3 + 4 + 5
15
>>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5
26
>>> accumulate(add, 11, 0, identity) # 11
11
>>> accumulate(add, 11, 3, square) # 11 + 1^2 + 2^2 + 3^2
25
>>> accumulate(mul, 2, 3, square) # 2 * 1^2 * 2^2 * 3^2
72
>>> # 2 + (1^2 + 1) + (2^2 + 1) + (3^2 + 1)
>>> accumulate(lambda x, y: x + y + 1, 2, 3, square)
19
>>> # ((2 * 1^2 * 2) * 2^2 * 2) * 3^2 * 2
>>> accumulate(lambda x, y: 2 * x * y, 2, 3, square)
576
>>> accumulate(lambda x, y: (x + y) % 17, 19, 20, square)
16
"""
return reduce(merger, list(map(term, list(range(1, n+1))))+[start])
summation_using_accumulate函数:
def summation_using_accumulate(n, term):
"""Returns the sum: term(0) + ... + term(n), using accumulate.
>>> summation_using_accumulate(5, square)
55
>>> summation_using_accumulate(5, triple)
45
>>> # You aren't expected to understand the code of this test.
>>> # Check that the bodies of the functions are just return statements.
>>> # If this errors, make sure you have removed the "***YOUR CODE HERE***".
>>> import inspect, ast
>>> [type(x).__name__ for x in ast.parse(inspect.getsource(summation_using_accumulate)).body[0].body]
['Expr', 'Return']
"""
return accumulate(add, 0, n, term)+term(0)
product_using_accumulate函数:
def product_using_accumulate(n, term):
"""Returns the product: term(1) * ... * term(n), using accumulate.
>>> product_using_accumulate(4, square)
576
>>> product_using_accumulate(6, triple)
524880
>>> # You aren't expected to understand the code of this test.
>>> # Check that the bodies of the functions are just return statements.
>>> # If this errors, make sure you have removed the "***YOUR CODE HERE***".
>>> import inspect, ast
>>> [type(x).__name__ for x in ast.parse(inspect.getsource(product_using_accumulate)).body[0].body]
['Expr', 'Return']
"""
return accumulate(mul, 1, n, term)
Q3: Filtered Accumulate
要求实现filtered_accumulate函数,添加过滤的功能:
def filtered_accumulate(merger, start, cond, n, term):
"""Return the result of merging the terms in a sequence of N terms
that satisfy the condition cond. merger is a two-argument function.
If v1, v2, ..., vk are the values in term(1), term(2), ..., term(N)
that satisfy cond, then the result is
start merger v1 merger v2 ... merger vk
(treating merger as if it were a binary operator, like +). The
implementation uses accumulate.
>>> filtered_accumulate(add, 0, lambda x: True, 5, identity) # 0 + 1 + 2 + 3 + 4 + 5
15
>>> filtered_accumulate(add, 11, lambda x: False, 5, identity) # 11
11
>>> filtered_accumulate(add, 0, odd, 5, identity) # 0 + 1 + 3 + 5
9
>>> filtered_accumulate(mul, 1, greater_than_5, 5, square) # 1 * 9 * 16 * 25
3600
>>> # Do not use while/for loops or recursion
>>> from construct_check import check
>>> # ban iteration and recursion
>>> check(HW_SOURCE_FILE, 'filtered_accumulate', ['While', 'For', 'Recursion'])
True
"""
def merge_if(x, y):
return merger(x, y) if cond(y) else x
return accumulate(merge_if, start, n, term)
Q4: Funception
要求实现funception函数:
def funception(func_a, start):
""" Takes in a function (function A) and a start value.
Returns a function (function B) that will find the product of
function A applied to the range of numbers from
start (inclusive) to stop (exclusive)
>>> def func_a(num):
... return num + 1
>>> func_b1 = funception(func_a, 0)
>>> func_b1(3) # func_a(0) * func_a(1) * func_a(2) = 1 * 2 * 3 = 6
6
>>> func_b2 = funception(func_a, 1)
>>> func_b2(4) # func_a(1) * func_a(2) * func_a(3) = 2 * 3 * 4 = 24
24
>>> func_b3 = funception(func_a, 3)
>>> func_b3(2) # Returns func_a(3) since start > stop
4
>>> func_b4 = funception(func_a, -2)
>>> func_b4(-3) # Returns None since start < 0
>>> func_b5 = funception(func_a, -1)
>>> func_b5(4) # Returns None since start < 0
"""
def func_b(end):
return reduce(mul, map(func_a, range(start+1, end)), func_a(start)) if start >=0 else None
return func_b
参考资料
Homework 2: Higher Order Functions:https://cs61a.org/hw/hw02/
[CS61A] Lecture 5&6&7. Environments & Design & Functions Examples & Homework 2: Higher Order Functions的更多相关文章
- 46 Simple Python Exercises-Higher order functions and list comprehensions
26. Using the higher order function reduce(), write a function max_in_list() that takes a list of nu ...
- [CS61A] Lecture 4. Higher-Order Functions & Project 1: The Game of Hog
[CS61A] Lecture 4. Higher-Order Functions & Project 1: The Game of Hog Lecture Lecture 4. Higher ...
- [CS61A] Lecture 1&2&3. Introduction&Functions&Control
[CS61A] Lecture 1&2&3. Introduction&Functions&Control 前言 CS61A是加州大学伯克利分校一门计算机专业课程,用于 ...
- 【原】Coursera—Andrew Ng机器学习—课程笔记 Lecture 11—Machine Learning System Design 机器学习系统设计
Lecture 11—Machine Learning System Design 11.1 垃圾邮件分类 本章中用一个实际例子: 垃圾邮件Spam的分类 来描述机器学习系统设计方法.首先来看两封邮件 ...
- magento app/design/adminhtml/default/default/template/sales/order/view/info.phtml XSS Vul
catalogue . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 Relevant Link: http://www.freebuf. ...
- 高级算法设计讲义 Lecture Notes for Advanced Algorithm Design
(Last modification: 2012-12-17) Textbooks: (1) David Williamson, David Shmoys. The Design of Approxi ...
- 《理解 ES6》阅读整理:函数(Functions)(七)Block-Level Functions
块级函数(Block-Level Functions) 在ES3及以前,在块内声明一个函数会报语法错误,但是所有的浏览器都支持块级函数.不幸的是,每个浏览器在支持块级函数方面都有一些细微的不同的行为. ...
- 《理解 ES6》阅读整理:函数(Functions)(四)Arrow Functions
箭头函数(Arrow Functions) 就像名字所说那样,箭头函数使用箭头(=>)来定义函数.与传统函数相比,箭头函数在多个地方表现不一样. 箭头函数语法(Arrow Function Sy ...
- 每个JavaScript开发人员应该知道的33个概念
每个JavaScript开发人员应该知道的33个概念 介绍 创建此存储库的目的是帮助开发人员在JavaScript中掌握他们的概念.这不是一项要求,而是未来研究的指南.它基于Stephen Curti ...
随机推荐
- OpenJudge1.5.17 菲波那契数列
17:菲波那契数列 总时间限制: 1000ms 内存限制: 65536kB 描述 菲波那契数列是指这样的数列: 数列的第一个和第二个数都为1,接下来每个数都等于前面2个数之和. 给出一个正整数k,要求 ...
- C#使用Spire.Pdf包对PDF文档进行数字签名
背景 对PDF文档进行数字签名的需求 对PDF文档添加水印的需求 网上资料版本不一或不全 本文章提到的Spire.Pdf均是使用的Spire.Pdf for .NET,除此之前还有其他语言的版本,如S ...
- CSS基础第一篇:图片插入<img>,文本空格
好家伙,这波是被迫回归基础 <img src="" alt=""> img代表"图像",它是图像在页面上显示.src代表&quo ...
- KingbaseES V8R3集群维护案例之---在线添加备库管理节点
案例说明: 在KingbaseES V8R3主备流复制的集群中 ,一般有两个节点是集群的管理节点,分为master和standby:如对于一主二备的架构,其中有两个节点是管理节点,三个数据节点:管理节 ...
- LIKE与等式查询比较
我们知道 char 是定长类型的数据,如果数据长度小于定义的长度,会在字符串尾部加上空格.而对于空格的处理,对于等式匹配,或length等,会忽略空格.而对于like 或模式匹配,空格不能忽略. 一. ...
- KingbaseFlySync 需要对外开放的端口
Oracle到kes双轨灾备场景 源:Oracle rac 11g 目标端:kes v8r6c4b21 源.目标.管控服务器IP 需要开放端口 为什么源和目标需要互相开放数据库端口:因为在双轨运行的方 ...
- React Native 入门 调试项目
不管时用哪种语言,哪种框架,调试永远都是一个避不开的话题 为我们提供了远程调试的功能,而这个功能需要Chrome浏览器的配合. 1. 首先浏览器一定要安装好React Developer Tool 插 ...
- Linux系统编程001--系统IO
1. 文件系统:用来存储.组织.管理文件的一套方式.协议 2. 文件 文件的属性:i-node唯一表示一个文件的存在与否 文件的内容 3. Linux系统如何实现文件的操作? 点击查看代码 硬件层: ...
- 几篇关于MySQL数据同步到Elasticsearch的文章---第五篇:logstash-input-jdbc实现mysql 与elasticsearch实时同步深入详解
文章转载自: https://blog.csdn.net/laoyang360/article/details/51747266 引言: elasticsearch 的出现使得我们的存储.检索数据更快 ...
- 定制开发 ERP 的优势有哪些?
定制开发ERP对企业而言是把双刃剑,成败难以把握.定制开发ERP理论上来讲是最贴合企业业务需求的,因为它是按企业需求定制,看上去似乎没什么毛病,但ERP是专业性极强的业务逻辑极其复杂的软件系统,有两个 ...