CS61A 2022 fall HW 01: Functions, Control

news2024/9/20 20:25:45

CS61A 2022 fall HW 01: Functions, Control

文章目录

  • CS61A 2022 fall HW 01: Functions, Control
    • Q1: A Plus Abs B
    • Q2: Two of Three
    • Q3: Largest Factor
    • Q4: Hailstone

HW01对应的是Textbook的1.1和1.2

Q1: A Plus Abs B

  • 题目:

    Fill in the blanks in the following function for adding a to the absolute value of b, without calling abs. You may not modify any of the provided code other than the two blanks.

    from operator import add, sub
    
    
    def a_plus_abs_b(a, b):
        """Return a+abs(b), but without calling abs.
    
        >>> a_plus_abs_b(2, 3)
        5
        >>> a_plus_abs_b(2, -3)
        5
        >>> a_plus_abs_b(-1, 4)
        3
        >>> a_plus_abs_b(-1, -4)
        3
        """
        if b < 0:
            f = _____
        else:
            f = _____
        return f(a, b)
    
  • solution

        if b < 0:
            f = sub
        else:
            f = add
        return f(a, b)
    

    在终端里面输入python ok -q a_plus_abs_b

    image-20230124194758963

    这题其实一开始我没反应过来,愣了一下,模块也能赋值给变量

    • 再验证一下这种用法

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k1wdMDJ4-1674571607986)(null)]

Q2: Two of Three

  • 题目

    Write a function that takes three positive numbers as arguments and returns the sum of the squares of the two smallest numbers. Use only a single line for the body of the function.

    def two_of_three(i, j, k):
        """Return m*m + n*n, where m and n are the two smallest members of the
        positive numbers i, j, and k.
    
        >>> two_of_three(1, 2, 3)
        5
        >>> two_of_three(5, 3, 1)
        10
        >>> two_of_three(10, 2, 8)
        68
        >>> two_of_three(5, 5, 5)
        50
        """
        return _____
    

    Hint: Consider using the max or min function:

    >>> max(1, 2, 3)
    3
    >>> min(-1, -2, -3)
    -3
    
  • solution

    呃,写这个的时候得把copilot关掉…不然copilot秒解

    • 看到hint其实思路就比较清晰了

      把三个的平方和加起来,然后减掉最大的那个数的平方

      return i*i + j*j + k*k - max(i, j, k)**2
      

    或者还有种方法

    return min(i*i+j*j,i*i+k*k,j*j+k*k)
    
  • python ok -q two_of_three

    image-20230124195643012

Q3: Largest Factor

  • Write a function that takes an integer n that is greater than 1 and returns the largest integer that is smaller than n and evenly divides n.

    def largest_factor(n):
        """Return the largest factor of n that is smaller than n.
    
        >>> largest_factor(15) # factors are 1, 3, 5
        5
        >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
        40
        >>> largest_factor(13) # factor is 1 since 13 is prime
        1
        """
        "*** YOUR CODE HERE ***"
    

Hint: To check if b evenly divides a, you can use the expression a % b == 0, which can be read as, “the remainder of dividing a by b is 0.”

  • solution

    def largest_factor(n):
        """Return the largest factor of n that is smaller than n.
    
        >>> largest_factor(15) # factors are 1, 3, 5
        5
        >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
        40
        >>> largest_factor(13) # factor is 1 since 13 is prime
        1
        """
        "*** YOUR CODE HERE ***"
        newlis = []
    
        for i in range(1,n):
            if n % i == 0:
                newlis.append(i)
        return newlis[len(newlis)-1]
    

    也可以反向做

    	factor = n - 1
        while factor > 0:
            if n % factor == 0:
                return factor
           	factor -= 1
    

image-20230124200259640

Q4: Hailstone

这个真是个经典例子, 在Linux C编程里讲到死循环的时候,还有邓俊辉《数据结构》里面讲到什么是算法的时候(考虑有穷性),都用到了这个例子

  • 题目

    Douglas Hofstadter’s Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.

    1. Pick a positive integer n as the start.
    2. If n is even, divide it by 2.
  1. If n is odd, multiply it by 3 and add 1.
  2. Continue this process until n is 1.

The number n will travel up and down but eventually end at 1 (at least for all numbers that have ever been tried – nobody has ever proved that the sequence will terminate). Analogously(类似地), a hailstone travels up and down in the atmosphere before eventually landing on earth.

This sequence of values of n is often called a Hailstone sequence. Write a function that takes a single argument with formal parameter name n, prints out the hailstone sequence starting at n, and returns the number of steps in the sequence:

def hailstone(n):
  """Print the hailstone sequence starting at n and return its
  length.

  >>> a = hailstone(10)
  10
  5
  16
  8
  4
  2
  1
  >>> a
  7
  >>> b = hailstone(1)
  1
  >>> b
  1
  """
  "*** YOUR CODE HERE ***"
  

Hailstone sequences can get quite long! Try 27. What’s the longest you can find?

Note that if n == 1 initially, then the sequence is one step long.
Hint: Recall the different outputs from using regular division / and floor division //

  • solution

    一开始我补充了这个代码,好像导致死循环了…?

        length = 1
        while n!=1:
            print(n)
            length += 1
            if n % 2 == 0:
                n /= 2
         
            if n % 2 != 0:
                n = 3 * n + 1
            
        print(1)
        return length
    
    

    image-20230124202721068

    image-20230124202435230

    然后我改成了 n //= 2,还是死循环啊啊啊啊啊


    恍然大悟!下面这两个if 不构成选择结构,还是顺序结构!!!

    如果n执行完第一个if变成奇数的话,他还会执行第二个if…呜呜呜

            if n % 2 == 0:
                n /= 2
         
            if n % 2 != 0:
                n = 3 * n + 1
    

    另外死循环主要是看控制条件哪里出错了,所以原因就应该去n上面找,按照这个思路来

    
    def hailstone(n):
        """Print the hailstone sequence starting at n and return its
        length.
    
        >>> a = hailstone(10)
        10
        5
        16
        8
        4
        2
        1
        >>> a
        7
        >>> b = hailstone(1)
        1
        >>> b
        1
        """
        "*** YOUR CODE HERE ***"
        length = 1
        while n != 1:
            print(n)
            length += 1
            if n % 2 == 0:
                n //= 2
    
            elif n % 2 != 0:
                n = 3 * n + 1
    
        print(1)
        return length
    
    

这个ok的评测机制应该是用的python的Doctests吧🤔

orz,怎么说呢,这个作业,反正是我在大学没有的体验

image-20230124200903663

  • 最后给的这个hailstone猜想的拓展阅读材料挺有意思的
    • https://www.quantamagazine.org/mathematician-proves-huge-result-on-dangerous-problem-20191211
  • 更好玩的是它给的一个网站
    • https://www.dcode.fr/collatz-conjecture

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

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

相关文章

Java | 解决并发修改异常问题【CurrentModificationException】

今日碰到Java中的一个异常&#xff0c;名为CurrentModificationException&#xff0c;从属于RunTimeException运行时异常&#xff0c;故作此记录 异常解析 首先来说明一下什么是【并发修改异常】❓ 因为迭代器依赖集合而存在&#xff0c;因为当你在操作集合中元素的时候&#…

springboot中restful风格请求的使用

springboot中restful风格请求的使用restful风格springboot中的使用1.创建html表单页面2.在yml配置文件中开启rest表单支持3.编写controller层及对应映射处理4.启动服务&#xff0c;逐个访问restful风格 Rest风格支持&#xff08;使用HTTP请求方式动词来表示对资源的操作&#…

【手写 Vue2.x 源码】第四十二篇 - 组件部分 - 组件挂载流程简述

一&#xff0c;前言 上篇&#xff0c;组件部分-生成组件的真实节点&#xff1b; 本篇&#xff0c;组件部分-组件挂载流程分析&#xff1b; 二&#xff0c;组件挂载流程分析 1&#xff0c;示例 全局组件&#xff1a;my-button&#xff0c;name&#xff1a;‘全局组件’&…

什么是软件架构中的ASRs(架构需求文档)?

作者&#xff1a;非妃是公主 专栏&#xff1a;《软件工程》 个性签&#xff1a;顺境不惰&#xff0c;逆境不馁&#xff0c;以心制境&#xff0c;万事可成。——曾国藩 专栏地址 软件工程专栏地址 专栏系列文章 软件工程复习01&#xff1a;软件工程概述 软件工程复习02&#xf…

十大经典排序算法(动态演示+代码)-快速排序与希尔排序

快速排序 1.什么是快速排序 我们知道排序有很多种&#xff0c;常见的如希尔排序&#xff0c;插入排序&#xff0c;选择排序&#xff0c;堆排序等等&#xff0c;而快速排序也是排序家族中的一员。因为其在大多数情况下有着优秀的综合性能&#xff0c;快速排序的快速也算是实至…

结构型模式-享元模式

1.概述 运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似对象的开销&#xff0c;从而提高系统资源的利用率。 2.结构 享元&#xff08;Flyweight &#xff09;模式中存在以下两种状态&#xff1a; 内…

信息论复习—信源编码的基本方法

目录 信源编码的目的&#xff1a;提高传输效率 离散信源&#xff1a; 离散信源的分类&#xff1a; 离散无记忆信源 (DMS: Discrete Memoryless Source&#xff09;&#xff1a; 离散无记忆信源的特点&#xff1a; 离散无记忆信源编码与译码&#xff1a; 等长编码的编码速…

Day869.索引(下) -MySQL实战

索引&#xff08;下&#xff09; Hi&#xff0c;我是阿昌&#xff0c;今天学习记录的是关于索引&#xff08;下&#xff09;的内容。 先来看一下这个问题&#xff1a; 下面这个表 T 中&#xff0c;如果执行 select * from T where k between 3 and 5&#xff0c;需要执行几次…

【Java|golang】1828. 统计一个圆中点的数目

给你一个数组 points &#xff0c;其中 points[i] [xi, yi] &#xff0c;表示第 i 个点在二维平面上的坐标。多个点可能会有 相同 的坐标。 同时给你一个数组 queries &#xff0c;其中 queries[j] [xj, yj, rj] &#xff0c;表示一个圆心在 (xj, yj) 且半径为 rj 的圆。 对…

git 操作整理

git操作整理 git 配置 git config --global user.name “yuluo” git config --global user.email “1481556636qq.com” git config --global color.ui auto 启用命令行着色输出 git 操作 暂存区 git init . 初始化git仓库 git status 看仓库状态 git add index.html…

【C++】C++11简介 | 列表初始化 | 声明 | 范围for

​&#x1f320; 作者&#xff1a;阿亮joy. &#x1f386;专栏&#xff1a;《吃透西嘎嘎》 &#x1f387; 座右铭&#xff1a;每个优秀的人都有一段沉默的时光&#xff0c;那段时光是付出了很多努力却得不到结果的日子&#xff0c;我们把它叫做扎根 目录&#x1f449;C11简介&…

安装配置Ecplise插件PyDev 8.3.0

参考&#xff1a;安装Eclipse&#xff1a;https://baijiahao.baidu.com/s?id1751992697661111503&wfrspider&forpcEclipse安装PyDev&#xff1a;https://baijiahao.baidu.com/s?id1746725485069671146&wfrspider&forpc方法一&#xff1a;失败打开eclipse&…

分享138个ASP源码,总有一款适合您

ASP源码 分享138个ASP源码&#xff0c;总有一款适合您 下面是文件的名字&#xff0c;我放了一些图片&#xff0c;文章里不是所有的图主要是放不下...&#xff0c; 138个ASP源码下载链接&#xff1a;https://pan.baidu.com/s/1idRmCxILGVt5pBkac-GiiA?pwdjmmu 提取码&#x…

AX7A200教程(4): DDR3的读写fifo仿真

在上篇博客中&#xff0c;我们只是进行突发读写&#xff0c;没有使用读写fifo对ddr3进行读写&#xff0c;因ddr3读写接口都是256位宽&#xff0c;所以ddr3的读写fifo输入和输出都是32位&#xff0c;和ddr3对接的接口都是256位&#xff0c;如下面示意图所示。下面的截图为ddr3的…

《c++ primer》第五章 语句

前言 建议看书的时候就看一下异常&#xff0c;其它的直接跳过 一、简单语句 ​ 一条表达式语句以;结尾&#xff0c;它的作用是执行表达式并丢弃掉求值结果。一行如果只有一个;也是一条语句&#xff0c;称为空语句。复合语句时用{}括起来的语句或者声明&#xff0c; 也称为块&a…

Qt之QLCDNumber

文章目录一、QLCDNumber简介二、QLCDNumber属性示例获取系统时间示例代码提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 一、QLCDNumber简介 QLCDNumber控件用于显示一个LCD数字。 它可以显示几乎任意大小的数字。可以显示十进制、十六进制、八进制或…

【并发编程】ForkJoin线程池

一、使用场景 用于CPU密集型的任务&#xff0c;通过把任务进行拆分&#xff0c;拆分成多个小任务去执行&#xff0c;然后小任务执行完毕后再把每个小任务执行的结果合并起来&#xff0c;这样就可以节省时间。 CPU密集型&#xff08;CPU-bound&#xff09;&#xff1a;CPU密集…

Java 初识IO流

IO流概述 用于读写文件中的数据&#xff08;可以读写文件&#xff0c;或网络中的数据…&#xff09; IO流的分类 纯文本文件:用windows系统自带的记事本打开并且能读懂的文件。如&#xff1a;txt文件、md文件、xml文件、lrc文件等. IO流的体系 总结 什么是IO流&#xff1f; 存…

Amesim2021.1与Simulink联合仿真配置流程及经验总结

Amesim 与 Simulink 联合仿真配置相对比较麻烦&#xff0c;笔者曾经凭运气配置成功过&#xff0c;但后来在别的电脑又多次配置失败&#xff0c;经过一些尝试及咨询专业人士&#xff0c;对Amesim2021.1版本与Simulink联合仿真配置做了一个流程总结&#xff0c;希望能帮助有需求的…

AutoSAR MemMap模块实例解析及注意事项

文章目录 1 AUTOSAR Memory Mapping的运行机制1.1 AUTOSAR Memory Mapping实例解析1.2 编译器的选择2 内存分配关键字3 如何生成BSW和 SWC的MemMap.h文件4 编译优化的影响传送门 ==>> AutoSAR入门和实战系列总目录 1 AUTOSAR Memory Mapping的运行机制 AUTOSAR Memory …