更好的阅读体验

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

CS61A Homework 5相关推荐

  1. CS61A Homework 7

    更好的阅读体验 Homework 7 Solutions hw07.zip Solution Files You can find the solutions in hw07.scm. Scheme ...

  2. CS61A 2022 fall lab0

    CS61A 2022 fall lab0:Getting Started 不得不感叹实验网站是真的高级- 打算用ubuntu做实验 文章目录 CS61A 2022 fall lab0:Getting ...

  3. CS61A学习笔记(作业篇)

    为了制止我半途而废,以及散落各处找不到的笔记,决定在这里记录学习笔记和作业遇到的困难等等. Lab 03 Q4: Repeated, repeated In Homework 2 you encoun ...

  4. nlp homework 03

    NLP Homework 03 --冯煜博 题目描述 (盒子和球模型)假设有3个盒子,每个盒子里装有红白两种颜色的球,盒子里的红白球有下表列出,初始状态分布. 解答 1. 给出HMM模型 \(\mu= ...

  5. HDU 5298 Solid Geometry Homework 暴力

    Solid Geometry Homework 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5298 Description Yellowstar ...

  6. HUST 1555 A Math Homework

    1555 - A Math Homework 时间限制:1秒 内存限制:128兆 338 次提交 131 次通过 题目描述 QKL is a poor and busy guy, and he was ...

  7. ACM Doing Homework again

    Ignatius刚刚从第30届ACM / ICPC回到学校.现在他有很多作业要做.每个老师给他一个截止作业的截止日期.如果Ignatius在截止日期之后进行了家庭作业,老师将减少他的最终考试成绩.现在 ...

  8. Codeforces Round #250 (Div. 2) A - The Child and Homework

    传送门Codeforces Round #250 (Div. 2) A - The Child and Homework 第一次做完之后交上去,过了例子.顺手就锁定了...然后一个小时之后就被HACK ...

  9. HDU 1789 Doing Homework again(馋)

    意甲冠军  参加大ACM竞争是非常回落乔布斯  每一个工作都有截止日期   未完成必要的期限结束的期限内扣除相应的积分   求点扣除的最低数量 把全部作业按扣分大小从大到小排序  然后就贪阿  能完毕 ...

最新文章

  1. NCEPU:线下组队学习周报(011)
  2. SAP创建Web Service以及用ABAP调用
  3. linux下redis权限,Linux(Centos)下Redis开机自启设置
  4. android模拟器 后退键,MainActivity返回键模拟home效果,容易出现的问题
  5. 成都Uber优步司机奖励政策(4月24日)
  6. self-利用self在类封装的方法中输出对象属性
  7. Linux 安装之U盘引导
  8. MyBatis学习笔记(一)——MyBatis快速入门
  9. Java中的锁(转)
  10. iphone怎么查看wifi密码_WiFi密码忘了怎么办?一秒找回密码
  11. 4十4十4写成乘法算式_小学数学二年级下册数学1-4单元知识点复习提前准备才能考的更好...
  12. linux安装pdo mysql扩展_linux下php安装pdo_mysql扩展
  13. 专访肖仰华:知识图谱迅速“升温”下的学习方法与就业选择
  14. python3使用paramiko
  15. 离散系统的李雅普诺夫稳定判据
  16. word转html在前端页面显示
  17. iOS7官方推荐图标和图像尺寸
  18. c语言定义数组uint,c - 将uint8_t数组转换为C中的uint16_t值 - 堆栈内存溢出
  19. Java二维数组的错误写法分析
  20. C++微信网页协议实现和应用

热门文章

  1. 如何修改数据库名字.sql文件
  2. mysql查 每一个月中的每一天的数据
  3. gRPC系列(三) 如何借助HTTP2实现传输
  4. vijos1264 lcs+ lis
  5. 金融风控:vintage、滚动率、迁徙率
  6. 比译 for Mac v0.3.5 划词/截图翻译
  7. android 修改手机系统,【教程贴丨09-29】手机系统APK自己来修改
  8. c语言中赋值的时候顿号的作用,简单总结C语言中的运算符优先级
  9. 以web api为基础开发的ai码平台
  10. 失事运输直升机残骸找到 机上人员全部遇难