CS61A Lab 4

news2024/11/16 20:41:15

更好的阅读体验

Lab 4: Recursion, Tree Recursion lab04.zip

What Would Python Do?

Q1: Squared Virahanka Fibonacci

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

python3 ok -q squared-virfib-wwpd -u✂️

Hint: If you are stuck, try drawing out the recursive call tree. See 02/11’s Lecture (Tree Recursion) for more information.

>>> def virfib_sq(n):
...     print(n)
...     if n <= 1:
...         return n
...     return (virfib_sq(n - 1) + virfib_sq(n - 2)) ** 2
>>> r0 = virfib_sq(0)
? 0
-- OK! --

>>> r1 = virfib_sq(1)
? 1
-- OK! --

>>> r2 = virfib_sq(2)

(line 1)? 2
(line 2)? 1
(line 3)? 0
-- OK! --

>>> r3 = virfib_sq(3)

(line 1)? 3
(line 2)? 2
(line 3)? 1
(line 4)? 0
(line 5)? 1
-- OK! --

>>> r3
? 4
-- OK! --

>>> (r1 + r2) ** 2
? 4
-- OK! --

>>> r4 = virfib_sq(4)

(line 1)? 4
(line 2)? 3
(line 3)? 2
(line 4)? 1
(line 5)? 0
(line 6)? 1
(line 7)? 2
(line 8)? 1
(line 9)? 0
-- OK! --

>>> r4
? 25
-- OK! --

Parsons Problems

To work on these problems, open the Parsons editor:

python3 parsons

Q2: Line Stepper

Complete the function line_stepper, which returns the number of ways there are to go from start to 0 on the number line by taking exactly k steps along the number line. Note that at each step, you must travel either left or right; you may not stay in place!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7cyFtIjp-1671289368934)(https://cs61a.org/lab/lab04/assets/line_stepper.png)]

For example, here is a visualization of all possible paths if we start at 3 on the number line with 5 steps. At every step, we move either one step to the left of right, and we ultimately end each path at 0.

def line_stepper(start, k):
    """
    Complete the function line_stepper, which returns the number of ways there are to go from
    start to 0 on the number line by taking exactly k steps along the number line.

    >>> line_stepper(1, 1)
    1
    >>> line_stepper(0, 2)
    2
    >>> line_stepper(-3, 3)
    1
    >>> line_stepper(3, 5)
    5
    """
    "*** YOUR CODE HERE ***"
    def line_stepper(start, k):
    if start == 0 and k == 0:
        return 1
    elif k == 0:
        return 0
    else:
        left = line_stepper(start - 1, k - 1)
        right = line_stepper(start + 1, k - 1)
        return left + right

Code Writing Questions

Q3: Summation

Write a recursive implementation of summation, which takes a positive integer n and a function term. It applies term to every number from 1 to n including n and returns the sum.

Important: Use recursion; the tests will fail if you use any loops (for, while).

def summation(n, term):
    """Return the sum of numbers 1 through n (including n) wíth term applied to each number.
    Implement using recursion!

    >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
    225
    >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
    54
    >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
    62
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> # ban iteration
    >>> check(HW_SOURCE_FILE, 'summation',
    ...       ['While', 'For'])
    True
    """
    assert n >= 1
    "*** YOUR CODE HERE ***"
    if n == 1:
        return term(n)
    else:
        return term(n) + summation(n - 1, term)

Use Ok to test your code:

python3 ok -q summation✂️

Q4: Insect Combinatorics

Consider an insect in an M by N grid. The insect starts at the bottom left corner, (1, 1), and wants to end up at the top right corner, (M, N). The insect is only capable of moving right or up. Write a function paths that takes a grid length and width and returns the number of different paths the insect can take from the start to the goal. (There is a closed-form solution to this problem, but try to answer it procedurally using recursion.)

grid

For example, the 2 by 2 grid has a total of two ways for the insect to move from the start to the goal. For the 3 by 3 grid, the insect has 6 diferent paths (only 3 are shown above).

Hint: What happens if we hit the top or rightmost edge?

def paths(m, n):
    """Return the number of paths from one corner of an
    M by N grid to the opposite corner.

    >>> paths(2, 2)
    2
    >>> paths(5, 7)
    210
    >>> paths(117, 1)
    1
    >>> paths(1, 157)
    1
    """
    "*** YOUR CODE HERE ***"
    if m == 1 and n == 1:
       return 1
    elif m == 0 or n == 0:
       return 0
    else:
        up = paths(m - 1, n)
        right = paths(m, n - 1)
        return up + right

Use Ok to test your code:

python3 ok -q paths✂️

Q5: Pascal’s Triangle

Pascal’s triangle gives the coefficients of a binomial expansion; if you expand the expression (a + b) ** n, all coefficients will be found on the nth row of the triangle, and the coefficient of the ith term will be at the ith column.

Here’s a part of the Pascal’s trangle:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Every number in Pascal’s triangle is defined as the sum of the item above it and the item above and to the left of it. Rows and columns are zero-indexed; that is, the first row is row 0 instead of 1 and the first column is column 0 instead of column 1. For example, the item at row 2, column 1 in Pascal’s triangle is 2.

Now, define the procedure pascal(row, column) which takes a row and a column, and finds the value of the item at that position in Pascal’s triangle. Note that Pascal’s triangle is only defined at certain areas; use 0 if the item does not exist. For the purposes of this question, you may also assume that row >= 0 and column >= 0.

def pascal(row, column):
    """Returns the value of the item in Pascal's Triangle
    whose position is specified by row and column.
    >>> pascal(0, 0)
    1
    >>> pascal(0, 5)	# Empty entry; outside of Pascal's Triangle
    0
    >>> pascal(3, 2)	# Row 3 (1 3 3 1), Column 2
    3
    >>> pascal(4, 2)     # Row 4 (1 4 6 4 1), Column 2
    6
    """
    "*** YOUR CODE HERE ***"
    if row == 0 and column == 0:
        return 1
    elif column == 0 or column == row:
        return 1
    elif column > row:
        return 0
    else:
        return pascal(row - 1, column - 1) + pascal(row - 1, column)
    

Use Ok to test your code:

python3 ok -q pascal✂️

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/96809.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CountDownLatch类的使用

&#x1f388;专栏链接:多线程相关知识详解 目录 一.CountDownLatch的介绍 二.CountDownLatch类里面的方法 三.CountDownLatch的两种应用场景 ①一等多情况 ②多等一情况 一.CountDownLatch的介绍 CountDownLatch是一种用来控制多线程的工具类,它被称为门阀、计数器或者…

LeetCode HOT 100 —— 301.删除无效的括号

题目 给你一个由若干括号和字母组成的字符串 s &#xff0c;删除最小数量的无效括号&#xff0c;使得输入的字符串有效。 返回所有可能的结果。答案可以按 任意顺序 返回。 思路 DFS 回溯算法&#xff1a; 首先最终合法的方案&#xff0c;必然有左括号的数量 右括号的数量 …

钉钉获取免登用户信息

大家好&#xff0c;这里是一口八宝周&#x1f44f; 欢迎来到我的博客❤️一起交流学习 文章中有需要改进的地方请大佬们多多指点 谢谢&#x1f64f; 最近好像搞了个什么钉钉小程序&#xff0c;具体做什么咱也不知道&#xff0c;就让我搞一个钉钉获取免登录用户信息的接口出来&…

计网理论模拟

一. 单选题&#xff08;共10 题&#xff0c;20.0分&#xff09; 1. (单选题,2.0分)网络协议主要由 3 个基本要素组成&#xff0c;即&#xff08; &#xff09; A. 层次、语义和同步B. 语法、原语和同步C. 语法、语义和同步D. 语法、语义和功能 正确答案: C 2. (单选题,2.0分…

计算机毕业设计ssm+vue基本微信小程序的智能图书管理系统

项目介绍 本设计旨在研究一种社区图书管理系统设计与实现系统,以各种浏览器web页面加上云服务器后端服务系统,通过这一设计过程,进一步熟悉web前端开发技术和云服务器后端开发技术和方法,培养理论联系实际及知识的综合运用能力。 图书管理系统可以有效实现图书管理的规范化、系…

SAP Gateway 后台模型的缓存设置

/iwbep/cl_mgw_med_provider 类里的成员 mv_cache_active: 这个 cache 默认是开启状态。 调用 OData 服务的 MPC_EXT 类的 get_last_modified 方法获取最后一次修改的时间戳。这个时间戳(timestamp)也会影响到 cache 的行为&#xff0c;我们后续也会详细讨论。 第12 行 super 方…

PySpark--spark local 的环境部署

Spark环境搭建-Local 环境搭建 基本原理 本质&#xff1a;启动一个JVM Process进程(一个进程里面有多个线程)&#xff0c;执行任务Task Local模式可以限制模拟Spark集群环境的线程数量, 即Local[N] 或 Local[*]其中N代表可以使用N个线程&#xff0c;每个线程拥有一个cpu core。…

【使用Netty实现群发消息】

使用Netty实现群发消息netty简单介绍实现群发流程图代码实现NettyServer 类MyChannelInitializer 类MyServerHandler 类ChannelHandler 类Netty 依赖效果展示netAssist 工具启动Netty server打开netAssist 工具netty简单介绍 Netty是由JBOSS提供的一个java开源框架&#xff0c…

第三十一章 linux-模块的加载过程

第三十一章 linux-模块的加载过程 文章目录第三十一章 linux-模块的加载过程sys_init_modulestruct moduleload_module在用户空间&#xff0c;用insmod这样的命令来向内核空间安装一个内核模块&#xff0c;本节将详细讨论模块加载时的内核行为。当调用“insmod demodev.ko”来安…

通讯录的思路与实现(C语言)

目录 前言 程序的分装 程序的结构 函数实现 通讯录的初始化 通讯录的扩容 将数据保存到本地 增加联系人 显示通讯录所有联系人 目标联系人的检索(根据名称) 目标联系人的检索(根据号码) 检索发展来的函数 删除联系人 查询目标联系人 联系人信息的更改 按名称对通…

Python写个“点球大战”小游戏

大家好&#xff0c;欢迎来到 Crossin的编程教室 &#xff01; 看过我Python入门教程的朋友应该会看到其中有提到一个点球小游戏的作业。 在世界杯决赛即将到来之际&#xff0c;我们再来回顾一下这个小游戏。对于刚刚学习编程不久的同学&#xff0c;这是个不错的练手习题&…

(二)RT-Thread入门——线程管理

目录 线程管理 线程管理特点 线程工作机制 线程控制块 线程属性 线程栈 线程状态 线程优先级 时间片 线程入口函数 无限循环模式 顺序执行或有限次循环模式 线程错误码 线程状态切换 线程操作 创建动态线程 删除 初始化静态线程 脱离 获得当前线程 让出…

数据结构基础篇》》用c语言实现复数的八个基本运算

数据结构开讲啦&#xff01;&#xff01;&#xff01;&#x1f388;&#x1f388;&#x1f388; 本专栏包括&#xff1a; 抽象数据类型线性表及其应用栈和队列及其应用串及其应用数组和广义表树、图及其应用存储管理、查找和排序将从简单的抽象数据类型出发&#xff0c;深入浅出…

B-013 缓启动电路设计

缓启动电路设计1 简介2 案例分析2.1 电路说明2.2 原理分析3 电路参数设定说明1 简介 缓启电路的供电是由一个PMOS控制通断的&#xff0c;软启动的设计是让PMOS的导通时间变缓&#xff0c;电路上的做法是在PMOS的栅极和源极之间接一个合适的电容&#xff0c;PMOS的导通时间就会…

Arcgis中创建Python脚本工具

文章目录创建工具步骤第一步&#xff1a;第二步&#xff1a;第三步&#xff1a;定义工具工具箱Toolbox工具类1、__init__2、getParameterInfo3、isLicensed4、updateParameters5、updateMessage6、execute进度条的使用代码相比于自定义工具箱的源脚本和参数定义难以集中管理的缺…

中国专利电子申请网站系统环境配置方法

一、在线平台使用环境要求 支持的操作系统、浏览器、office的版本如下&#xff0c;必须匹配对应的版本&#xff1a; 操作系统&#xff1a;WINDOWS XP、WINDOWS 7、WINDOWS 8 浏览器&#xff1a;IE8、IE9、IE10 文档编辑软件&#xff1a;OFFICE2003、OFFICE2007 强烈推荐使用中…

1. Maven基础

1. Maven简介 Maven是专门用于管理和构建Java项目的工具&#xff0c;它的主要功能有&#xff1a; 提供了一套标准化的项目结构 提供了一套标准化的构建流程&#xff08;编译&#xff0c;测试&#xff0c;打包&#xff0c;发布……&#xff09; 提供了一套依赖管理机制 1.1…

Allegro快速编辑丝印文字操作指导

Allegro快速编辑丝印文字操作指导 Allegro支持丝印文字的编辑,下面介绍快速编辑丝印文字的两种方法如下 以编辑下方丝印文字为例 方法一: 选择Text edit 命令 点击丝印文字,丝印会被高亮起来 输入需要更改后的文字,如下 右击选择done 文字被更改好了 方法二 选择se…

Function composition

In mathematics, function composition is an operation  ∘  that takes two functions f and g, and produces a function h g  ∘  f such that h(x) g(f(x)). In this operation, the function g is applied to the result of applying the function f to x. That is…