CS61A Homework 5

news/2024/11/28 21:51:03/

更好的阅读体验

Homework 5: Trees, Linked Lists hw05.zip

Mid-Semester Feedback

Q1: Mid-Semester Feedback

As part of this week’s homework, please fill out the Mid-Semester Feedback form.

This survey is designed to help us make short term adjustments to the course so that it works better for you. We appreciate your feedback. We may not be able to make every change that you request, but we will read all the feedback and consider it.

Confidentiality: Your responses to the survey are confidential, and only the instructor (Pamela) and head TA (Vanshaj) will be able to see this data unanonymized. More specifics on confidentiality can be found on the survey itself.

Once you finish the survey, you will be presented with a passphrase (if you miss it, it should also be at the bottom of the confirmation email you receive). Put this passphrase, as a string, on the line that says passphrase = '*** PASSPHRASE HERE ***' in the Python file for this assignment.

Use Ok to test your code:

python3 ok -q midsem_survey✂️

Parsons Problems

Q2: Chain

For this question, we will define a chain as a path from the root of a tree t to any leaf such that all nodes on the path share the same label. Implement the function chain, which, given a tree t, returns True if there exists any chain in the tree, and False otherwise.

def chain(t):"""Returns whether there exists a path in t where all nodesshare the same label.>>> all_fives = Tree(5, [Tree(5), Tree(5, [Tree(5)])])>>> chain(all_fives)True>>> t1 = Tree(1, [Tree(3, [Tree(4)]), Tree(1)])>>> chain(t1)True>>> t2 = Tree(1, [Tree(3, [Tree(4)]), Tree(5)])>>> chain(t2)False""""*** YOUR CODE HERE ***"if t.is_leaf():return Truefor b in t.branches:if t.label == b.label and chain(b):return Truereturn False

Q3: Flatten Link

Write a function flatten_link that takes in a linked list lnk and returns the sequence as a Python list. If lnk has nested linked lists, flatten_link should flatten lnk.

def flatten_link(lnk):"""Takes a linked list and returns a flattened Python list with the same elements.>>> link = Link(1, Link(2, Link(3, Link(4))))>>> flatten_link(link)[1, 2, 3, 4]>>> flatten_link(Link.empty)[]>>> deep_link = Link(Link(1, Link(2, Link(3, Link(4)))), Link(Link(5), Link(6)))>>> flatten_link(deep_link)[1, 2, 3, 4, 5, 6]""""*** YOUR CODE HERE ***"if lnk is Link.empty:return []if isinstance(lnk.first, Link):return flatten_link(lnk.first) + flatten_link(lnk.rest)return [lnk.first] + flatten_link(lnk.rest)

Code Writing Questions

Q4: Has Path

Write a function has_path that takes in a Tree t and a string term. It returns True if there is a path that starts from the root where the entries along the path spell out the term, and False otherwise. You may assume that every node’s label is exactly one character.

This data structure is called a trie, and it has a lot of cool applications, such as autocomplete.

def has_path(t, term):"""Return whether there is a path in a Tree where the entries along the pathspell out a particular term.>>> greetings = Tree('h', [Tree('i'),...                        Tree('e', [Tree('l', [Tree('l', [Tree('o')])]),...                                   Tree('y')])])>>> print(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>>> has_path(greetings, 'hint')False"""assert len(term) > 0, 'no path for empty term.'"*** YOUR CODE HERE ***"if len(term) == 1:return str(t.label) == term[0]flag = Falseif str(t.label) == term[0]:for b in t.branches:if str(b.label) == term[1]:flag = has_path(b, term[1:])return flag

Use Ok to test your code:

python3 ok -q has_path✂️

Q5: Duplicate Link

Write a function duplicate_link that takes in a linked list lnk and a value. duplicate_link will mutate lnk such that if there is a linked list node that has a first equal to value, that node will be duplicated. Note that you should be mutating the original link list lnk; you will need to create new Links, but you should not be returning a new linked list.

Note: in order to insert a link into a linked list, you need to modify the .rest of certain links. We encourage you to draw out a doctest to visualize!

def duplicate_link(lnk, val):"""Mutates `lnk` such that if there is a linked listnode that has a first equal to value, that node willbe duplicated. Note that you should be mutating theoriginal link list.>>> x = Link(5, Link(4, Link(3)))>>> duplicate_link(x, 5)>>> xLink(5, Link(5, Link(4, Link(3))))>>> y = Link(2, Link(4, Link(6, Link(8))))>>> duplicate_link(y, 10)>>> yLink(2, Link(4, Link(6, Link(8))))""""*** YOUR CODE HERE ***"def duplicate(lnk, val):new_lnk = Link(val, lnk)return new_lnkif int(lnk.first) == val:new_lnk = duplicate(lnk.rest, val)lnk.rest = new_lnk

Use Ok to test your code:

python3 ok -q duplicate_link✂️

Q6: Mutable Mapping

Implement deep_map_mut(fn, link), which applies a function fn onto all elements in the given linked list lnk. If an element is itself a linked list, apply fn to each of its elements, and so on.

Your implementation should mutate the original linked list. Do not create any new linked lists.

Hint: The built-in isinstance function may be useful.

>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> isinstance(s, Link)
True
>>> isinstance(s, int)
False

Construct Check: The last doctest of this question ensures that you do not create new linked lists. If you are failing this doctest, ensure that you are not creating link lists by calling the constructor, i.e.

s = Link(1)
def deep_map_mut(fn, lnk):"""Mutates a deep link lnk by replacing each item found with theresult of calling fn on the item.  Does NOT create new Links (sono use of Link's constructor).Does not return the modified Link object.>>> link1 = Link(3, Link(Link(4), Link(5, Link(6))))>>> # Disallow the use of making new Links before calling deep_map_mut>>> Link.__init__, hold = lambda *args: print("Do not create any new Links."), Link.__init__>>> try:...     deep_map_mut(lambda x: x * x, link1)... finally:...     Link.__init__ = hold>>> print(link1)<9 <16> 25 36>""""*** YOUR CODE HERE ***"while lnk:if isinstance(lnk.first, Link):deep_map_mut(fn, lnk.first)else:lnk.first = fn(lnk.first)lnk = lnk.rest

Use Ok to test your code:

python3 ok -q deep_map_mut✂️

Submit

Make sure to submit this assignment by running:

python3 ok --submit

Optional Questions

Homework assignments will also contain prior exam-level questions for you to take a look at. These questions have no submission component; feel free to attempt them if you’d like a challenge!

  1. Spring 2018 MT2 Q5ab: Trees
  2. Spring 2019 MT2 Q6a: Trie this
  3. Fall 2017 Final Q4a: O! Pascal

http://www.ppmy.cn/news/4039.html

相关文章

蓝牙款血氧仪单片机开发

本文为大家介绍便携式智能血氧仪的监测应用方案。血氧仪主要测量指标分别为脉率、血氧饱和度、灌注指数&#xff08;PI&#xff09;。血氧饱和度&#xff08;oxygen saturation简写为SpO2&#xff09;是临床医疗上重要的基础数据之一。血氧饱和度是指在全部血容量中被结合O2容量…

猿如意中【ndm】助你轻松管理你的 NPM包

目录 一、ndm 简介 1.1、下载 ndm-1.exe 版本&#xff08;v1.2.0&#xff09; 1.2、安装 1.3、版本迭代更新记录 1.3.1、ndm v0.1.4 已发布https://github.com/720kb/ndm/releases/tag/v0.1.4 1.3.2、ndm v1.0.0 发布&#xff0c;现已完全跨平台Windows、Mac、Linux 1.3.3、…

电商之收单系统的webhook推送重试机制

文章目录1 问题背景2 前言3 解决方案3.1 核心思路3.2 数据库设计3.3 下一次发送webhook的时间算法3.3 详细设计4 延申思考1 问题背景 作为一个收单系统&#xff0c;当获取到一笔交易的支付结果时&#xff0c;就需要发送一个webhook消息给电商系统。电商系统收到webhook消息后&a…

【Python机器学习】Sklearn库中Kmeans类、超参数K值确定、特征归一化的讲解(图文解释)

一、局部最优解 采用随机产生初始簇中心 的方法&#xff0c;可能会出现运行 结果不一致的情况。这是 因为不同的初始簇中心使 得算法可能收敛到不同的 局部极小值。 不能收敛到全局最小值&#xff0c;是最优化计算中常常遇到的问题。有一类称为凸优化的优化计算&#xff0c;不…

03-MySQL查询数据

目录 DQL语言 单表查询 AS子句 DISTINCT关键字的使用 WHERE条件语句 逻辑操作符 比较操作符 BETWEEN范围查询 LIKE模糊查询 使用IN进行范围查询 NULL空值条件查询 连接查询&#xff08;多表查询&#xff09; INNER JOIN内连接 等值和非等值的连接查询 外连接 JOIN对比…

中小企业OA系统的设计与实现

开发工具(eclipse/idea/vscode等)&#xff1a; 数据库(sqlite/mysql/sqlserver等)&#xff1a; 功能模块(请用文字描述&#xff0c;至少200字)&#xff1a; 模块划分&#xff1a;通知类型模块、通知信息模块、部门模块、员工模块、考勤模块、工资模块、奖惩类型、奖惩信息、请假…

高比例风电电力系统储能运行及配置分析(Matlab实现)

目录 0 概述 1 案例及分析及分析 2 Matlab实现 3 结论 运行结果 目录 0 概述 1 案例及分析及分析 2 Matlab实现 3 结论 0 概述 高比例风电电力系统储能运行及配置分析 1 案例及分析及分析 针对附件2所示的十五天负荷功率&#xff08;最大值1200MW&#xff09;、风电功…

冰刃(IceSword)的使用方法(基础篇)

冰刃是一款功能强大的杀毒辅助软件&#xff0c;深受很多杀毒高手的青睐&#xff0c;这里我介绍一下冰刃这个软件的简单使用方法&#xff0c;供大家参考。说句实话&#xff0c;我不是高手&#xff0c;不能像高手一样把一些软件运用自如&#xff0c;所以这个方法可能有很多纰漏或…