Fall 2020 Berkeley cs61a hw03答案
Fall 2020 Berkeley cs61a hw03答案
HW_SOURCE_FILE=__file__def mobile(left, right):"""Construct a mobile from a left arm and a right arm."""assert is_arm(left), "left must be a arm"assert is_arm(right), "right must be a arm"return ['mobile', left, right]def is_mobile(m):"""Return whether m is a mobile."""return type(m) == list and len(m) == 3 and m[0] == 'mobile'def left(m):"""Select the left arm of a mobile."""assert is_mobile(m), "must call left on a mobile"return m[1]def right(m):"""Select the right arm of a mobile."""assert is_mobile(m), "must call right on a mobile"return m[2]def arm(length, mobile_or_planet):"""Construct a arm: a length of rod with a mobile or planet at the end."""assert is_mobile(mobile_or_planet) or is_planet(mobile_or_planet)return ['arm', length, mobile_or_planet]def is_arm(s):"""Return whether s is a arm."""return type(s) == list and len(s) == 3 and s[0] == 'arm'def length(s):"""Select the length of a arm."""assert is_arm(s), "must call length on a arm"return s[1]def end(s):"""Select the mobile or planet hanging at the end of a arm."""assert is_arm(s), "must call end on a arm"return s[2]def planet(size):"""Construct a planet of some size."""assert size > 0"*** YOUR CODE HERE ***"return ['planet', size]def size(w):"""Select the size of a planet."""assert is_planet(w), 'must call size on a planet'"*** YOUR CODE HERE ***"return w[1]def is_planet(w):"""Whether w is a planet."""return type(w) == list and len(w) == 2 and w[0] == 'planet'def examples():t = mobile(arm(1, planet(2)),arm(2, planet(1)))u = mobile(arm(5, planet(1)),arm(1, mobile(arm(2, planet(3)),arm(3, planet(2)))))v = mobile(arm(4, t), arm(2, u))return (t, u, v)def total_weight(m):"""Return the total weight of m, a planet or mobile.>>> t, u, v = examples()>>> total_weight(t)3>>> total_weight(u)6>>> total_weight(v)9>>> from construct_check import check>>> # checking for abstraction barrier violations by banning indexing>>> check(HW_SOURCE_FILE, 'total_weight', ['Index'])True"""if is_planet(m):return size(m)else:assert is_mobile(m), "must get total weight of a mobile or a planet"return total_weight(end(left(m))) + total_weight(end(right(m)))def balanced(m):"""Return whether m is balanced.>>> t, u, v = examples()>>> balanced(t)True>>> balanced(v)True>>> w = mobile(arm(3, t), arm(2, u))>>> balanced(w)False>>> balanced(mobile(arm(1, v), arm(1, w)))False>>> balanced(mobile(arm(1, w), arm(1, v)))False>>> from construct_check import check>>> # checking for abstraction barrier violations by banning indexing>>> check(HW_SOURCE_FILE, 'balanced', ['Index'])True""""*** YOUR CODE HERE ***"if total_weight(end(left(m))) * length(left(m)) == total_weight(end(right(m))) * length(right(m)):if is_planet(end(left(m))) and is_planet(end(right(m))):return Trueelif is_planet(end(left(m))):if not balanced(end(right((m)))):return Falseelif is_planet(end(left(m))):if not balanced(end(right((m)))):return Falseelse:for i in [left(m), right(m)]:if not balanced(end(i)):return Falsereturn Trueelse:return Falsedef totals_tree(m):"""Return a tree representing the mobile with its total weight at the root.>>> t, u, v = examples()>>> print_tree(totals_tree(t))321>>> print_tree(totals_tree(u))61532>>> print_tree(totals_tree(v))932161532>>> from construct_check import check>>> # checking for abstraction barrier violations by banning indexing>>> check(HW_SOURCE_FILE, 'totals_tree', ['Index'])True""""*** YOUR CODE HERE ***"if is_planet(m):return tree(size(m))return tree(total_weight(m), [totals_tree(i) for i in [end(left(m)), end(right(m))]])def replace_leaf(t, find_value, replace_value):"""Returns a new tree where every leaf value equal to find_value hasbeen replaced with replace_value.>>> yggdrasil = tree('odin',... [tree('balder',... [tree('thor'),... tree('freya')]),... tree('frigg',... [tree('thor')]),... tree('thor',... [tree('sif'),... tree('thor')]),... tree('thor')])>>> laerad = copy_tree(yggdrasil) # copy yggdrasil for testing purposes>>> print_tree(replace_leaf(yggdrasil, 'thor', 'freya'))odinbalderfreyafreyafriggfreyathorsiffreyafreya>>> laerad == yggdrasil # Make sure original tree is unmodifiedTrue""""*** YOUR CODE HERE ***"if is_leaf(t):if label(t) == find_value:t = tree(replace_value)return treturn tree(label(t), [replace_leaf(branch, find_value, replace_value) for branch in branches(t)])def preorder(t):"""Return a list of the entries in this tree in the order that theywould be visited by a preorder traversal (see problem description).>>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])>>> preorder(numbers)[1, 2, 3, 4, 5, 6, 7]>>> preorder(tree(2, [tree(4, [tree(6)])]))[2, 4, 6]""""*** YOUR CODE HERE ***"if is_leaf(t):return [label(t)]k = [label(t)]for branch in branches(t):k = k + preorder(branch)return kdef depth_of_tree(t):if is_leaf(t):return 1return max([1 + depth_of_tree(branch) for branch in branches(t)])def has_path(t, word):"""Return whether there is a path in a tree where the entries along the pathspell out a particular word.>>> greetings = tree('h', [tree('i'),... tree('e', [tree('l', [tree('l', [tree('o')])]),... tree('y')])])>>> print_tree(greetings)hielloy>>> has_path(greetings, 'h')True>>> has_path(greetings, 'i')False>>> has_path(greetings, 'hi')True>>> has_path(greetings, 'hello')True>>> has_path(greetings, 'hey')True>>> has_path(greetings, 'bye')False"""assert len(word) > 0, 'no path for empty word.'"*** YOUR CODE HERE ***"if depth_of_tree(t) < len(word):return Falseelse:if len(word) == 1 and label(t) == word[0]:return Trueelif label(t) != word[0]:return Falseelif label(t) == word[0]:for branch in branches(t):if has_path(branch, word[1:]):return Truereturn Falsedef interval(a, b):"""Construct an interval from a to b."""return [a, b]def lower_bound(x):"""Return the lower bound of interval x.""""*** YOUR CODE HERE ***"def upper_bound(x):"""Return the upper bound of interval x.""""*** YOUR CODE HERE ***"
def str_interval(x):"""Return a string representation of interval x."""return '{0} to {1}'.format(lower_bound(x), upper_bound(x))def add_interval(x, y):"""Return an interval that contains the sum of any value in interval x andany value in interval y."""lower = lower_bound(x) + lower_bound(y)upper = upper_bound(x) + upper_bound(y)return interval(lower, upper)
def mul_interval(x, y):"""Return the interval that contains the product of any value in x and anyvalue in y."""p1 = x[0] * y[0]p2 = x[0] * y[1]p3 = x[1] * y[0]p4 = x[1] * y[1]return [min(p1, p2, p3, p4), max(p1, p2, p3, p4)]def sub_interval(x, y):"""Return the interval that contains the difference between any value in xand any value in y.""""*** YOUR CODE HERE ***"def div_interval(x, y):"""Return the interval that contains the quotient of any value in x divided byany value in y. Division is implemented as the multiplication of x by thereciprocal of y.""""*** YOUR CODE HERE ***"reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))return mul_interval(x, reciprocal_y)def par1(r1, r2):return div_interval(mul_interval(r1, r2), add_interval(r1, r2))def par2(r1, r2):one = interval(1, 1)rep_r1 = div_interval(one, r1)rep_r2 = div_interval(one, r2)return div_interval(one, add_interval(rep_r1, rep_r2))
def check_par():"""Return two intervals that give different results for parallel resistors.>>> r1, r2 = check_par()>>> x = par1(r1, r2)>>> y = par2(r1, r2)>>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)True"""r1 = interval(1, 1) # Replace this line!r2 = interval(1, 1) # Replace this line!return r1, r2def multiple_references_explanation():return """The multiple reference problem..."""def quadratic(x, a, b, c):"""Return the interval that is the range of the quadratic defined bycoefficients a, b, and c, for domain interval x.>>> str_interval(quadratic(interval(0, 2), -2, 3, -1))'-3 to 0.125'>>> str_interval(quadratic(interval(1, 3), 2, -3, 1))'0 to 10'""""*** YOUR CODE HERE ***"# Tree ADTdef tree(label, branches=[]):"""Construct a tree with the given label value and a list of branches."""for branch in branches:assert is_tree(branch), 'branches must be trees'return [label] + list(branches)def label(tree):"""Return the label value of a tree."""return tree[0]def branches(tree):"""Return the list of branches of the given tree."""return tree[1:]def is_tree(tree):"""Returns True if the given tree is a tree, and False otherwise."""if type(tree) != list or len(tree) < 1:return Falsefor branch in branches(tree):if not is_tree(branch):return Falsereturn Truedef is_leaf(tree):"""Returns True if the given tree's list of branches is empty, and Falseotherwise."""return not branches(tree)def print_tree(t, indent=0):"""Print a representation of this tree in which each node isindented by two spaces times its depth from the root.>>> print_tree(tree(1))1>>> print_tree(tree(1, [tree(2)]))12>>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])>>> print_tree(numbers)1234567"""print(' ' * indent + str(label(t)))for b in branches(t):print_tree(b, indent + 1)def copy_tree(t):"""Returns a copy of t. Only for testing purposes.>>> t = tree(5)>>> copy = copy_tree(t)>>> t = tree(6)>>> print_tree(copy)5"""return tree(label(t), [copy_tree(b) for b in branches(t)])
Fall 2020 Berkeley cs61a hw03答案相关推荐
- Fall 2020 Berkeley cs61a hw01答案
Fall 2020 Berkeley cs61a hw01答案 from operator import add, subdef a_plus_abs_b(a, b):""&quo ...
- Fall 2020 Berkeley cs61a Hog Project
** Fall 2020 Berkeley cs61a Hog Project ** Fall 2020 的Hog和之前project有些变化,Github找不到,所以分享一下- "&quo ...
- 2020年高压电工答案解析及高压电工考试平台
题库来源:安全生产模拟考试一点通公众号小程序 2020年高压电工答案解析及高压电工考试平台,包含高压电工答案解析答案和解析及高压电工考试平台练习.由安全生产模拟考试一点通公众号结合国家高压电工考试最新 ...
- 2020年高压电工答案解析及高压电工新版试题
题库来源:安全生产模拟考试一点通公众号小程序 2020年高压电工答案解析及高压电工新版试题,包含高压电工答案解析答案和解析及高压电工新版试题练习.由安全生产模拟考试一点通公众号结合国家高压电工考试最新 ...
- 2020 UCB CS61A FALL -- project1 hog
UCB2020的秋季课,老师是Hany Farid和John DeNero hog是第一个项目,做的时候感觉细节挺多的,主要是熟悉下python的一些语法和高阶函数的使用 代码 "" ...
- 2020 android面试题答案
(1)java面试题(基础+进阶)(必须) java中==和equals和hashCode的区别 ==是运算符,用来比较两个值.两个对象的内存地址是否相等: equals是Object类的方法,默认情 ...
- 2020年计算机考试题答案,2020年《计算机绘图》考试试题附全答案【完整版】
<2020年<计算机绘图>考试试题附全答案[完整版]>由会员分享,可在线阅读,更多相关<2020年<计算机绘图>考试试题附全答案[完整版](6页珍藏版)> ...
- 2020中考计算机统考答案,2020中考必读 | 中考电脑阅卷流程“潜规则”!读完孩子少丢20分!(转给中考生)...
今天和大家来聊一聊考试阅卷的那些事情... 现在的考试都趋于正规.公平化,特别是中考和高考这两场重要的升学考试,全国统一采取电子阅卷的方式来给学生阅卷. 而大部分平时的模拟考试都不是电脑阅卷,又加上很 ...
- 组合求解器 + 深度学习 =?这篇ICLR 2020论文告诉你答案
2020-01-26 20:17:46 选自TowadsDataScience 作者:Marin Vlastelica Pogančić 机器之心编译 参与:郭元晨.魔王 如何将组合求解器无缝融入深度 ...
- 2020大学计算机知到答案,2020年_知到_大学计算机(济南大学)_网课答案
摘要: ... 确定设备更新的依据是( ). A:设备的自然寿命 B:设备的技术寿命 C:设备的经济寿命 D:设备的有效寿命 正确答案:C 答案解析:在设备更新分析中,经济寿命是确定设备最优更新期的 ...
最新文章
- 推荐一款 Flutter Push 推送功能插件
- Firefox跟博客园闹别扭!用不了博客园的HTML编辑器了。
- APP运营如何找到精准用户,提升品牌知名度
- python获取绝对路径_python 获取文件本身的绝对路径
- python高阶函数、map reduce 自己如何去定义_「python」高阶函数map、reduce的介绍
- UVa 3349 Snowflake Snow Snowflakes(Hash)
- 三校生计算机word基础知识,三校生计算机第一次月考计算机基础、word.doc
- 5.15 vs2019 静态编译_xmake v2.3.8 发布, 新增 Intel C++/Fortran 编译器支持
- LeetCode 242. 有效的字母异位词 (计数排序思想字符处理)
- 三极晶体管放大电路实验
- linux进程map,linux内存优化一文中 查看进程mem_map 的实现
- 【数据结构】C++STL map 常见用法小结
- WPS专业版自带字体
- 3-20模拟赛【果冻之王】题解
- html背景纯白,纯白色背景图片全白
- dft频谱泄漏matlab,对于DFT频谱泄漏问题的研究
- 第9章 Linux的磁盘管理
- 如何在金仓数据库KingbaseES中使用pg_get_function_arg_default函数
- matlab示波器有功功率,巧用示波器计算功率
- 介绍python中几种遍历列表的for循环方法