Tutorial - Software Engineering

icon
password

Python基本语法

基本的Python表达式与运算符

  • 算术运算符和整除 (//): 题目2019S1-1。
    • 2023S1-12(算术)
    • 2023S1-20(使用bool进行逻辑评估)
  • 列表的拼接: 题目2019S1-2。
    • 2023S1-10(列表连接)
    • 2023S1-29(字符串修改,这是一个错误)
  • 元组的拼接: 题目2019S1-3。
  • 逻辑运算符和比较运算符: 题目2019S1-4。
  • 变量和赋值: 2023S1-30(打印时进行字符串连接)、2023S1-4 私有变量命名的约定、2023S1-18 用于改变私有属性的访问。
💡
对Python基本运算符的理解,包括算术、逻辑、比较和数据结构(列表、元组)的基本运算。

运算符与整除

Operator
Name
Description
a + b
Addition
Sum of a and b
a - b
Subtraction
Difference of a and b
a * b
Multiplication
Product of a and b
a / b
True division
Quotient of a and b
a // b
Floor division
Quotient of a and b, removing fractional parts
a % b
Modulus
Integer remainder after division of a by b
a ** b
Exponentiation
a raised to the power of b
-a
Negation
The negative of a
在Python中,// 是整除运算符,它返回两个数相除后的整数部分
math.floor()
math.ceil()
Operation
Description
Operation
Description
a == b
a equal to b
a != b
a not equal to b
a < b
a less than b
a > b
a greater than b
a <= b
a less than or equal to b
a >= b
a greater than or equal to b
💡
逻辑运算符的优先顺序 not > and > or

List (stack/queue)

在Python中,列表(list)是一个有序的元素集合。列表中的元素可以是任意数据类型,包括数字、字符串、甚至其他列表。列表用方括号 [] 表示,元素之间用逗号分隔。
  1. 索引访问:使用索引(index)来访问列表中的单个元素。Python中的索引从0开始。
    1. 负数索引:使用负数索引可以从列表末尾开始访问元素。
      1. 切片操作:使用冒号 : 来访问列表的一个范围(切片),可以取出列表的一个子集。
        1. 步长:在切片操作中可以指定步长(stride),用来在指定范围内“跳过”一定数量的元素。
          1. 修改列表:列表是可变的,这意味着你可以更改列表中的元素。
            1. 删除元素:可以使用 del 语句根据索引来删除列表中的元素。
              如果你尝试访问列表中不存在的索引,Python会抛出一个 IndexError 异常。因此,在尝试访问列表元素之前,确保索引在列表的有效范围内是很重要的。
              1. Append方法:planets.append('Pluto')
              1. Extend方法:只能加列表,如果加的是int就会报int错误
                1. TypeError: 'int' object is not iterable

              Tuple 元组

              • 创建之后不可改变里面的元素
              • 它可以作为dict的key

              @2023S1

              1. (2023S1)Suppose we want to define a name for maximum volume that is intended to be private. Which name is most appropriate?
                1. A. __maximum_volume__:我这个方法不公开,你无法从外部调用
                  🔥
                  无法通过a.__maximum_volume__调用
                  a._Dancebot__maximum_volume__()
                  B. MaximumVolume C. _maximum_volume: 你需要注意这个method是我写的哈哈 D. MAXIMUM_VOLUME.
              sol
              c 前缀下划线()是约定俗成的方式,用来指示变量或函数是私有的,意味着它们不是为了公共使用。
              • A. __maximum_volume__(双下划线前后缀)通常用于Python中的特殊方法或“魔术”方法,这些方法意图被Python系统本身使用。它们并不是为了限制访问权限而设置为“私有”的,但它们在语言内部有特定用途。
              • B. MaximumVolume(帕斯卡命名法)通常用于很多编程语言中的类名,包括Python。
              • C. _maximum_volume(单下划线前缀)是Python中的一个约定,表示一个变量或方法是用于内部使用的(即按照约定是“私有的”,但语言并不严格执行)。
              • D. MAXIMUM_VOLUME(全部大写并用下划线分隔)通常用于表示程序执行过程中不应更改的常量。它并不暗示隐私,而是用来表示这个值在代码中应该保持不变。

              10. (2023S1)What does the following expression evaluate to?
              A. '9876' B. ['9876'] C. ['98', '76'] D. Error
              sol
              c

              12. (2023S1)What does the following expression evaluate to?
              A. 0 B. 6 C. 7 D. Error
              sol
              b

              18. (2023S1)What is the purpose of "setter" methods as they pertain to objects? A. They are used to change the values of private variables. B. They are used to retrieve the values of private variables. C. They allow private variables to be manipulated by multiple instances of the same class. D. They are used to write data to files.
              sol
              a 在面向对象的编程范式中,setter方法是一种特殊的方法,允许外部代码安全地改变对象的私有属性或变量的值。私有变量通常是不允许直接从对象外部访问和修改的,以避免对象的状态被无意或恶意地损坏。通过使用setter方法,开发者可以控制如何以及何时修改这些私有变量,包括进行验证或其他逻辑处理。
              选项B描述的是“getter”方法的功能,它们用于检索私有变量的值。 选项C并不准确,因为setter方法本身并不允许私有变量被多个实例操作;它们只是提供了一个接口来修改这些变量。 选项D描述的是与文件IO相关的操作,与setter方法无关。
              notion image

              20. (2023S1)How many of the following expressions evaluate to True?
              A. 1 B. 2 C. 3 D. 4
              sol
              C 在Python中,bool() 函数用来将值转换成布尔值。默认情况下,只有少数几个值被认为是假(False),比如:
              • None
              • False
              • 任何数值类型的零(0, 0.0, 0j等)
              • 空序列('', (), [])
              • 空映射({})
              • 以及定义了__bool__()__len__() 方法的类的实例,如果这个方法返回 False0

              1. bool("") —— 空字符串,被认为是False
              1. bool(" ") —— 包含一个空格的字符串,被认为是True,因为它不是空的。
              1. bool([0]) —— 列表中虽然只有一个元素0(其布尔值为False),但列表本身不为空,所以这是True
              1. bool(-1) —— 任何非零数值都被认为是True,即便它是负数。
              因此,除了第一个表达式以外,其它三个表达式都会评估为True

              29. (2023S1)Suppose the following lines of code have been executed.
              What is stored in drake._num_good_songs?
              A. 0 B. 1 C. 'Drake' D. Error
              sol
              a
              drake

              30. (2023S1)Given the following code:
              and assuming the user inputs 4 then 0. What is output?
              A. x + y = x + y B. x + y = 4 C. x + y = 4 + 0 D. x + y = 40
              sol
              d 当用户首先输入4,然后输入0时,x将会是字符串"4"y将会是字符串"0"。在print语句中,字符串的加法操作将会执行字符串连接,而不是数值的相加。

              @2019S1

              1. (2019S1)What does the expression evaluate to?
              sol
              notion image
              2. (2019S1)What does the expression evaluate to?
              sol
              [1, 2, 2, 3]
              notion image
              3. (2019S1)What does the expression evaluate to?
              sol
              tuple 和 list 一样
              4. (2019S1)What does the expression (0 < 2 < 4 and not 3 > 0 > 1) evaluate to?
              sol
              True
              notion image

              数据结构操作

              1. List
              1. Tuple
              1. Dict
                1. get方法,有两个参数,三个参数会给type error
                2. 第一个参数就是找key
                3. 第二个参数是default value,如果这个字典不存在第一个参数的key,那么就返回这个第二个参数
              1. String
              1. Set
              • 字符串连接和变量赋值: 题目2019S1-5、2019S1-6。
              • 列表索引和切片: 题目2019S1-7、2019S1-8、2019S1-9。
                • 列表索引和切片: 2023S1-6(切片), 2023S1-7(索引可能出现IndexError
                • 2023S1-25 不是有效Python列表的选项
              • 字典操作和方法: 题目2019S1-10、2019S1-11。
                • 字典键: 2023S1-1(可以作为字典键的类型)
                • 字符串操作和赋值: 2023S1-19(字符串的不可变性)
              🔥
              列表传递共享一个内存地址;因为list有一个可变性质;整数,字符串和tuple不可变
              💡
              对Python内置数据结构(列表、字符串、字典)的操作能力,包括索引、切片、方法调用、键值对的处理等。

              @2023S1

              1. (2023S1)Which of the following cannot be a key in a dictionary.
              A. '123' B. (1, 2, 3) C. 123 D. [1, 2, 3]
              sol
              d
              列表不可哈希,因此不能作为字典的键

              1. (2023S1)Suppose the following has been executed by Python.
              What is stored in ys?
              A. [4, 5] B. [4, 5, 6] C. [5, 4] D. []
              sol
              a
              在Python中,列表切片的语法是list[start:stop],其中start索引是包含在切片内的,而stop索引是不包含的。切片操作会返回列表的一个部分。
              对于xs[-3:-1]
              • 3表示从列表的倒数第三个元素开始(在这个例子中是数字4),
              • 1表示到列表的倒数第一个元素的前一个结束(也就是说,不包括倒数第一个元素,这里是数字6)。
              所以ys将包含列表xs的从倒数第三个到倒数第二个元素,但不包括倒数第一个元素。
              xs = [1, 2, 3, 4, 5, 6]
              • xs[-3]4
              • xs[-2]5

              1. (2023S1)Which option will throw an IndexError in the following code when replacing #sub?
              A. xs[-len(xs)] B. xs[1-len(xs)] C. xs[-1-len(xs)] D. xs[len(xs)-1]
              sol
              c
              在Python中,IndexError通常在尝试访问序列中不存在的索引时抛出。
              A. xs[-len(xs)]: 这相当于xs[-4],由于列表xs长度为4,-len(xs)指向的是列表的第一个元素。这不会抛出IndexError
              B. xs[1-len(xs)]: 这相当于xs[1-4],即xs[-3]。列表中的第三个元素从左边数(索引2),或者从右边数(索引-3),也不会抛出IndexError
              C. xs[-1-len(xs)]: 这相当于xs[-1-4],即xs[-5]。因为xs列表中没有索引-5的元素(最小的有效负索引是-4,对应于列表的第一个元素),这将会抛出IndexError
              D. xs[len(xs)-1]: 这相当于xs[4-1],即xs[3],是列表中的最后一个有效索引,因此不会抛出IndexError

              19. (2023S1)What is the value of ys after the following is executed?
              A. "hello world" B. "Hello World" C. "xs" D. Error
              sol
              d
              字符串是不可变的

              25. (2023S1)Which of the following is not a valid list in Python?
              A. ['one', 2, '3', 'IV'] B. [1, int(2), [{}], 4.0] C. [1, [False, True], int(2), True] D. All are valid lists.
              sol
              d
              A. ['one', 2, '3', 'IV'] - 包含字符串和整数的列表。
              B. [1, int(2), [{}], 4.0] - 包含整数、通过int函数得到的整数、包含一个空字典的列表以及一个浮点数的列表。
              C. [1, [False, True], int(2), True] - 包含整数、布尔值列表、通过int函数得到的整数以及布尔值的列表。

              @2019S1

              5. (2019S1)After the assignment s1= "Programming" + " is " + "Fun", which of the following statements assigns "is" to s2?
              sol
              b 和 d都对
              notion image
              6. (2019S1)What is the value of s4 after the following statements are evaluated?
              s1 = "Hello" s2 = "World" s3 = "Ni Hao" s3 = s1 s3 = "Hi" s4 = s1 + s2
              sol
              notion image
              1. (2019S1)What is the value of a after the following statements are evaluated? x = ['x', 'y', 'z'] y = ['z', 'y', 'x'] z = x + y a = z[1]
              sol
              notion image
              1. (2019S1)What is the value of x after the following statements are evaluated? x = [-1, 1.5, 'a'] y = x y[2] = 0
              sol
              notion image
              1. (2019S1)What is the value of x after the following statements are evaluated?
              sol
              notion image
              1. (2019S1)Why can a list not be used as a key for a value in a dictionary? i.e. The following code will raise an error:
              a) The Python interpreter cannot determine which list value to use as the key. b) A list may be empty, so its contents cannot be hashed to generate an index. c) Dictionary keys must be immutable types, so that the key’s index does not change. d) Lists may contain elements of different types and all keys in a dictionary must be of the same type.
              sol
              notion image

              1. (2019S1)What is the value of d after the following statements are evaluated?
              sol
              notion image

              控制流和循环

              • 2023S1-9(循环中的条件,评估bool表达式)
              • while 循环: 题目2019S1-14。
              • ifelif 条件语句: 题目2019S1-15。
                • 2023S1-15(关于if-then-else结构的逻辑陈述)
              • for 循环和条件语句结合使用: 题目2019S1-16。
                • For循环和Range: 2023S1-23(使用range并更新变量)
              💡
              编程逻辑和对Python控制流结构的使用,如循环和条件分支。

              @2023S1

              1. (2023S1)What is stored in count after the following is evaluated?
              A. 0 B. 3 C. 4 D. 6
              sol
              d
              if (x == "a") or ("c") or ("e") or ("g"):
              在Python中,非空字符串总是被评估为True。因此,表达式"c""e""g"在布尔上下文中都是True,所以无论x的值是什么,条件总是为True

              15. (2023S1)Which of the following statements is True? A. Python will prohibit the modification of globally defined user constants like PI = 3.14. B. The body of a while loop must execute at least once. C. Every if-then-else statement can be written using only if-then statements. D. The order that Python statements are given has no effect on the program’s output.
              sol
              C
              A. 在Python中,并没有内置的常量的概念,虽然我们可以约定用大写变量作为“常量”表示,但这并不能阻止它们被修改。
              B. while循环在条件首次检查就为假时,可能一次也不执行。
              C. 可以通过使用多个if语句,并且通过适当的逻辑来控制,使其等效于if-then-else语句。
              D. 在大多数情况下,语句的顺序直接影响了程序的输出。例如,赋值语句的顺序改变可能会导致变量存储不同的值。

              23. (2023S1)What error is raised after executing the following?
              A. TypeError B. ValueError C. NameError D. No error is generated.
              sol
              c count 没有 提前定义 count = 0

              @2019S1

              1. (2019S1)What is output after the following code is executed?
              sol
              notion image

              1. (2019S1)What is output after the following code is executed?
              sol
              notion image

              1. (2019S1)What is output after the following code is executed?
              sol
              notion image

              函数与递归

              • 函数定义和调用: 题目2019S1-12、2019S1-13、2019S1-20、
                • 2023S1-2(函数返回值与打印), 2023S1-11(函数在返回值上的行为)
              • 递归函数: 题目2019S1-23、
                • 2023S1-5(递归函数调用和基本情况),
                • 2023S1-21(完成递归函数)
              • 函数的参数传递: 题目2019S1-17(假设lst是函数的参数)。
              • 参数和类型提示: 2023S1-3(类型提示), 2023S1-17(由于错误的参数类型导致类型错误), 2023S1-22(函数参数的类型提示)
              • 特定函数使用:2023S1-8 用于给小部件添加事件处理器。(bind()用于将函数绑定到小部件事件)、2023S1-13 tk.TOP(为了让标签叠在一起,使用'side=tk.TOP')
              • 2023S1-28 返回值
              💡
              对函数定义、作用域、参数传递以及递归逻辑的理解。

              函数

              strip() split()
              1. .strip(): 这个方法去除了字符串两端的空白字符,包括空格、制表符、换行符等。行的开始和结束没有多余的空格或换行字符。
              1. .split(','): 这个方法根据逗号分隔字符串,并返回一个字符串列表。
              假设原始文件wind_speed.csv中的一行是这样的:
              在应用day.strip()之后,这行字符串两端的空白字符(如果有的话)会被移除。但是对于这个例子,由于没有空白字符,结果将会和原字符串一样:
              然后应用day.split(','),会按逗号分隔字符串,得到以下列表:
              这个列表中的每个元素都是字符串类型的数字,可以进一步转换为整数或浮点数以进行计算。

              @2023S1

              1. (2023S1)Suppose the following functions have been defined.
              Which of the following expressions will cause an error?
              A. z = foo(3) B. z = bar(3) C. z = 2 * foo(3) D. z = 2 * bar(3)
              sol
              D. z = 2 * bar(3)(bar函数打印但不返回值,因此不能被乘)
              1. (2023S1)Recall def foo(x: int) -> int: is type-hinted whereas def bar(): is not. What statement is true about type-hints (i.e. type contracts). A. Type-hints signal the user of the expected input to a function. B. Type-hints are enforced. That is, if you pass a function a value with a different type than what is type-hinted Python will throw an error. C. Python will throw an error if a function is not type-hinted. D. None of the above.
              sol
              A. 类型提示用于向函数用户表明预期的输入。(Python中类型提示不是强制的)
              5. (2023S1)Suppose the following functions have been defined.
              What will foo(0) return?
              A. -1 B. 0 C. 1 D. Error
              sol
              d
              x 在函数中没有被定义。

              8. (2023S1)What is the purpose of the bind() method in tkinter? A. To create a new widget. B. To add an event handler to a widget. C. To remove a widget from a window. D. To resize a widget.
              sol
              b
              在 tkinter GUI 库中,bind() 方法的目的是将一个事件处理函数关联到一个特定的事件。当特定的事件发生时(如用户点击按钮或移动鼠标),相关联的函数会被调用。因此,bind() 方法通常用于为小部件添加事件处理程序。

              11. (2023S1)Consider the following function.
              Which option bests describes the behaviour of foo when invoked properly? A. True only when count is positive. B. True only when count is negative or zero. C. Always False. D. Always True.
              sol
              c
              因为 while 循环会将 count 增加直到它不再是负数,所以返回时 count 必定不小于0。这意味着 count < 0 将总是 False

              13. (2023S1)Consider the following incomplete code.
              notion image
              What do we assign this_side in order to produce the following window? pdf page575
              A. tk.LEFT B. tk.RIGHT C. tk.TOP D. tk.BOTTOM
              sol
              b
              notion image

              17. (2023S1)What error, if any, does Python raise when the following is executed?
              A. TypeError B. ValueError C. NameError D. No error is generated.
              sol
              d
              在Python中,类型注解(如函数头中的 x: str-> str仅供参考,不会强制执行类型检查。这意味着尽管函数期望一个字符串,但传递非字符串类型的参数不会直接导致类型错误。
              因此,尽管类型注解指明了字符串类型,实际上没有违反Python的类型规则,也没有其他语法或运行时错误。所以代码将会执行而不会引发错误,只是返回值类型与函数签名中的返回类型注解不匹配。

              21. (2023S1)The following is a recursive function with a partially implemented base case; it concatenates a list of strings. What should we replace #sub with to complete this function?
              A. (0, xs[0]) B. (1, xs[0]) C. (0, "") D. (1, "")
              sol
              c
              为了正确实现这个递归函数,我们需要定义一个基础情况,当列表为空时(即 len(xss) == 0),应该返回一个空字符串 "",因为没有更多的字符串可以连接。
              所以我们需要的是:
              • n 应该为 0,这是基础情况的条件,表示列表中没有字符串。
              • base 应该为 "",表示一个空的累积值。
              22. (2023S1)What is the most appropriate type hint (i.e. type contract) for the following?
              A. foo(x: int, y: str) -> str: B. foo(x: int, y: list[str]) -> str: C. foo(x: list[int], y: str) -> str: D. foo(x: list[int], y: list[str]) -> list[str]:
              sol
              c
              Python中字符串可以通过与整数相乘来重复
              所以我们需要的类型提示是:
              • x 应该是包含整数的列表(因为你可以用整数来乘字符串)。
              • y 应该是包含字符串的列表(因为字符串可以被整数相乘来进行重复)。
              • 返回类型应该是字符串(因为 ans 是通过累加字符串创建的)。
               

              28. (2023S1)Suppose the following function definition has been made.
              What is type(foo(1, 2))?
              A. <class 'int'> B. <class 'float'> C. <class 'str'> D. <class 'NoneType'>
              sol
              在Python中,如果函数不显式返回任何值,它默认返回None

              @2019S1

              12. (2019S1)What is the value of the global variable a after the following code is executed?
              sol
              notion image

              1. (2019S1)What is the value of x after the following code is executed?
              sol
              notion image

              1. (2019S1)Assuming that the parameter lst is a list of integer values, which of the following descriptions best describe the purpose of this function?
              sol
              notion image
              1. (2019S1)For the following function:
              What will r(5) return?
              sol
              notion image

              1. (2019S1)The following is a recursive function to check to see if an item is in a list of numbers. It assumes that the values in alist are stored in ascending order.
              Which code fragments will correctly complete the function above?
              a)
              Fragment 1 is: True
              Fragment 2 is: in_list(alist[:midpoint], item)
              Fragment 3 is: in_list(alist[midpoint+1:], item) b)
              Fragment 1 is: True
              Fragment 2 is: in_list(alist[midpoint+1:], item)
              Fragment 3 is: in_list(alist[:midpoint], item) c)
              Fragment 1 is: False
              Fragment 2 is: in_list(alist[:midpoint], item)
              Fragment 3 is: in_list(alist[midpoint+1:], item) d)
              Fragment 1 is: False
              Fragment 2 is: in_list(alist[midpoint+1:], item)
              Fragment 3 is: in_list(alist[:midpoint], item) e)
              None of the code fragments would implement the function correctly.
              sol
              notion image

              Python编程风格和异常处理

              • 全局变量和常量的使用: 2019S1-18、
                • 2023S1-14(While循环和变量修改), 2023S1-15(对循环体执行的误解), 2023S1-16(评估空列表)、2023S1-24(全局变量)
              • try 语句和异常处理: 题目2019S1-19、2019S1-20。
              • 错误处理: 2023S1-26(不返回列表的列表方法), 2023S1-27(由于不正确的类型转换导致的错误)
              • 代码简化和可读性: 题目2019S1-21、2019S1-22。
              💡
              编码风格,如何使用全局变量和常量,异常处理的方式,以及如何编写清晰可读的代码。
              Error 类型
              notion image

              @2023S1

              14. (2023S1)What is the value of zs after the following is evaluated?
              A. ['t', ['a', 'b', 'c']] B. ['t', 'a', 'b', 'c'] C. ['t', ['c', 'a', 'b']] D. ['t', 'c', 'a', 'b']
              sol
              A

              16. (2023S1)Suppose xs is a list. Which expression evaluates to True when xs is empty.
              A. bool(not xs) B. bool(xs) C. bool(len(xs)) D. bool(xs is [])
              sol
              a
              A. 当 xs 为空时,not xsTrue(因为 not 一个空列表返回 True),所以 bool(not xs) 将会是 True
              B. False,因为直接将一个空列表转换为布尔值结果是 False
              C. 当 xs 为空时,len(xs) 返回 0,而 bool(0)False
              D. 始终是 False,即使 xs 为空,因为 is 运算符检查两边的对象身份是否相同,而 [] 是在每次执行时创建的一个新的列表,因此它的身份与 xs 不同,除非 xs 明确地指向这个新的列表。

              24. (2023S1)Which function requires the use of a a global variable to be implemented? A. A function that calls itself. B. A function that returns the number of times the function has been called. C. A function that calls a different function. D. A function that prints and returns a value.
              sol
              b
              需要一个全局变量来跟踪函数被调用的次数
              A. 递归函数(调用自身的函数)不需要全局变量,它们通过递归的方式工作。 C. 一个函数调用另一个函数并不要求有全局变量,除非它需要访问或修改全局状态。 D. 仅打印和返回一个值的函数不需要全局变量。

              26. (2023S1)What is stored in xs after the following is executed?
              A. [1, 2, 3] B. [3, 2, 1] C. None D. Error
              sol
              c list.reverse() 方法是就地反转列表中的元素,这意味着它直接修改列表并返回 None。所以当你将 xs.reverse() 的结果赋值给 xs 时,实际上是将 None 赋值给了 xs
              xs = [1, 2, 3] xs.reverse() # 这是就地反转,不返回列表

              27. (2023S1)What error is generated by executing the following?
              A. TypeError B. ValueError C. NameError D. No error is generated.
              sol
              b

              @2019S1

              1. (2019S1)Why are global constants considered to be good programming style, while global variables are bad programming style? a) Global constants are still global values and are bad programming style and should be avoided. b) In the Python interpreter, as global constants do not change value, they can be cached in high speed memory to provide faster lookup times for their values. c) Constants do not change value, so they allow meaningful names to be given to commonly used values that can be referenced anywhere in a program. d) Both (b) and (c).
              sol
              notion image

              1. (2019S1)What is the purpose of the try statement in Python? a) To indicate that the code has encountered an error it cannot handle locally. b) To provide an error handling function that will be called if any error occurs in a block of code. c) To guarantee that any errors raised by a block of code will be handled, so that the program will not crash. d) To attempt to execute a block of code and handle at least some of the errors that may be raised by the statements in the block of code.
              sol
              notion image

              1. (2019S1)What is output after the following code is executed:
              sol
              notion image

              1. (2019S1)For the following block of code:
              Which of the following programming constructs would best simplify the above code?
              sol
              notion image

              1. (2019S1)For the following block of code:
              Which of the following programming constructs would best simplify the above code?
              a) tuple b) dictionary c) if statement d) while loop e) function
              sol

              代码题

              文件IO

              (2023S1) Q36
              Write a function foo that satisfies the following specification
              sol
              strip() split()
              1. .strip(): 这个方法去除了字符串两端的空白字符,包括空格、制表符、换行符等。行的开始和结束没有多余的空格或换行字符。
              1. .split(','): 这个方法根据逗号分隔字符串,并返回一个字符串列表。
              假设原始文件wind_speed.csv中的一行是这样的:
              在应用day.strip()之后,这行字符串两端的空白字符(如果有的话)会被移除。但是对于这个例子,由于没有空白字符,结果将会和原字符串一样:
              然后应用day.split(),会按逗号分隔字符串,得到以下列表:
              这个列表中的每个元素都是字符串类型的数字,可以进一步转换为整数或浮点数以进行计算。

              (2019S1) Q25 - 27
              The next three questions refer to the following function definition, which is missing three lines of code. The function reads raw wind speed data from a file and calculates the average and maximum wind speeds for each day. The following is an example of a data file (wind_speed.csv).
              接下来的三个问题参考了下面的函数定义,其中缺少三行代码。该函数从文件中读取原始风速数据,并计算每天的平均风速和最大风速。以下是数据文件 (wind_speed.csv) 的示例。 12,15,8,24,2,15 22,12,19,29,16,13 11,5,7,3,5,9,2,4,1,3,5,7,12,8,11 Each line of the file contains the wind speed readings collected on a single day. These values may be integer or floating point and are separated by a comma. Each day may have different numbers of readings. The average wind speed for a day is simply the average of all the values on the line. The maximum wind speed for a day is the largest value on the line. The results are written to an output file in the same order in which they are read from the input file. The logic assumes that the data in the input file is in the correct format.
              文件的每一行包含一天收集的风速读数。这些值可以是整数或浮点值,并用逗号分隔。每天的阅读次数可能不同。一天的平均风速就是线上所有值的平均值。一天的最大风速是线上的最大值。结果按照从输入文件读取的顺序写入输出文件。该逻辑假设输入文件中的数据格式正确。
              The definition of the process function, with three missing lines, is given below.
              The result of calling the completed function on the file described above, for example by:

              sol
              先看语法
              对于 ## line 1: Set initial max wind speed ## 需要的代码是:
              这一行代码将列表wind_speeds的第一个元素(一个字符串)转换为浮点数,并将其设为初始的最大风速max_wind_speed
              对于 ## line 2: Calculate average and max wind speeds ## 需要的代码是:
              在这段代码中,wind_speeds是一个字符串列表,代表风速的值。我们需要将每个字符串转换为浮点数进行数学运算,并将其加到total变量上,以便后续计算平均风速。
              对于 ## line 3: Update max wind speed ## 需要的代码是:
              这行代码应该在循环内,也就是在将wind_speed转换为浮点数并加到total之后。它会在当前的wind_speed大于目前的max_wind_speed时更新max_wind_speed

              OOP

              (2023S1) Q31 - 35
              4
              a 是 A 类的实例,A 的 g 方法返回传入参数的两倍。
              a.g(2) # 返回 2 * 2,即 4。
              3
              A 的 f 方法调用 g 方法并从结果中减去 1。
              由于 a 是 A 的实例,调用的是 A 的 g 方法。
              a.f(2) # 返回 a.g(2) - 1,即 4 - 1。
              6
              a 是 A 类的实例,A 的 g 方法返回传入参数的两倍。
              a.g(3) # 返回 2 * 3,即 6。
              5
              A 的 f 方法调用 g 方法并从结果中减去 1。
              由于 a 是 A 的实例,调用的是 A 的 g 方法。
              a.f(3) # 返回 a.g(3) - 1,即 6 - 1。
              2
              d 是 D 类的实例。D 继承了 B 并覆盖了 f 和 g 方法。
              D 的 f 方法调用 B 的 f 方法并从返回值中减去传入的参数 x。
              B 的 f 方法(A 的 f 方法被 B 继承)调用 g 方法并减去 1。
              由于 D 覆盖了 g 方法,调用的是 D 的 g 方法。
              D 的 g 方法返回 self.y + y,此时 self.y 是 3(从构造函数中 self.x += y 得出)。
              d.g(2) # 返回 3 + 2,即 5。
              因此 B 的 f 方法返回 d.g(2) - 1,即 5 - 1,结果是 4。
              最后 D 的 f 方法返回 super().f(x) - x,即 4 - 2,结果是 2。

              (2019S1) Q28 - 30
              The following partial definition of a student class is used in the following three questions.
              sol
              对于 ## code block 1 ##,正确的代码是:
              这一行代码将课程代码(course_code)作为键,学生成绩(grade)作为值,添加到_results这个字典中。
              对于 ## code block 2 ##,正确的代码是:
              这一段代码计算了所有成绩的总和,然后除以成绩的数量来计算平均成绩,即GPA。使用self._results.items()可以获取字典中所有的键值对。
              最后,对于执行之后输出"GPA is: 6.0"的代码块,正确的是:
              这组语句正确地对me这个Student实例调用了add_result方法,并且通过get_gpa方法计算和输出了GPA。其他选项要么是错误的调用方式,要么是语法错误。
              1. (2019S1) What is an advantage of using classes to structure your program over just using functions? a) Classes provide a mechanism to encapsulate data and behaviour together. This means that only the methods defined in the class will manipulate an object’s data. Consequently, there is less chance of unknown parts of a program using an object’s data and breaking the program’s logic.
                1. a)
                  正确。类提供了一种封装数据和行为的机制。这意味着只有类中定义的方法才能操作对象的数据。因此,程序的其余未知部分使用对象数据的机会减少了,这降低了破坏程序逻辑的风险。这是面向对象编程(OOP)的基本原则之一,称为封装。
                  b) Classes are a mechanism to group related functions together that reduces the amount of code that needs to be written in each function. This mechanism inherently reduces duplication between similar functions. Consequently, using classes improves your code readability.
                  b)
                  错误。虽然类确实将相关函数组合在一起,但这本身并不减少每个函数中需要编写的代码量。类不是直接减少函数中代码重复的机制;相反,它提供了一种组织和复用代码的方式。代码可读性的提高是因为类提供了清晰的组织结构和定义明确的行为界限,而不是因为减少了代码量。
                  c) Classes provide a mechanism to group related functions into a single file. This simplifies maintenance of the code, as all similar functionality is stored in a single file. Consequently, it is faster to search for the implementation of functionality across files in the file system.
                  c)
                  错误。将相关函数分组到单个文件中是模块化编程的概念,这可以适用于函数和类。虽然类确实帮助组织相关的功能,但它们的主要优势不在于简化代码维护或搜索实现的速度。
                  notion image
                  d) Classes make it easier to reuse code. Whenever a programmer wants to reuse a method, they can inherit from the class that defines the method and then call that method in their code. Consequently, it simplifies access to existing methods.
                  d)
                  类确实使得代码重用更加容易,特别是通过继承。当程序员想要重用一个方法时,他们可以从定义该方法的类继承,并在他们的代码中调用该方法。但是,这个选项忽略了继承是面向对象编程中的一个特性,而不是类本身的一个特性函数也可以被重用,尽管没有继承机制。
                  e) None of the answers above are valid descriptions of an advantage of using classes to structure your program over just using functions.
                  e)
                  错误。以上有至少一个正确描述使用类的优势的答案。
               
              (2019S1) Q32 - 35
              4
              a 是类 A 的一个实例,而且 A 的方法 g 定义为返回参数的平方
              a.g(2) # 返回 2 * 2,即 4
              7
              b.f(3) # 调用 A 的 f 方法,它返回 self.g(3) + 1 # 因为 B 覆盖了 g 方法,所以这里调用的是 B 的 g 方法 # B 的 g 方法返回 self._x * y,此处 self._x 是 2,y 是 3 # 所以结果是 2 * 3 + 1 = 6 + 1 = 7
              8
              c.g(2) # 调用 B 的 g 方法,返回 self._x * y,此处 self._x 是 4,y 是 2 # 所以结果是 4 * 2 = 8
              6 super() - 用基类方法
              d.f(2) # 调用 D 的 f 方法,它返回 super().f(x) * x # 这里的 super().f(x) 调用 B 的 f 方法,因为 D 直接继承 B # B 的 f 方法会调用 B 的 g 方法并加 1,但是此时 g 方法会调用的是 D 的 g 方法 # D 的 g 方法返回 self._y * y,此时 self._y 是 1,y 是 2 # 所以 super().f(2) 是 1 * 2 + 1 = 3 # D 的 f 方法会返回上面的结果乘以 x,即 3 * 2 = 6

              (2019S1) Q36 - 38
              The application has two buttons and a label. The label is initially “Good Day”. When started, the GUI appears as in the image below.
              notion image
              Clicking on the button labelled “Aussie”, changes the label to be “G’Day”. Clicking on the button labelled “French”, changes the label to be “Bonjour”. The code is provided below.
              d
              ## code block 1 ## 需要创建按钮,并将它们绑定到对应的事件处理函数。
              这是因为 command 参数需要一个函数引用,而不是函数的执行结果。选项 a) 和 c) 错误地使用了 () 调用了方法,这会导致函数立即执行,而不是当按钮被点击时执行。
              notion image
              b
              What is the time complexity, in terms of the length of the list of values, of the following function that returns the index of the largest value in the list? You may assume accessing elements of a list, determining the length of a list and arithmetic operations are all constant time operations.
              关于函数 find_largest 的时间复杂度。
              这个函数通过迭代一次列表 values 来查找最大值的索引。因此,无论列表的长度为多少,它总是检查每个元素一次,这意味着时间复杂度是与列表长度成线性关系的。所以正确答案是:
              该函数没有嵌套循环(不是二次),也不是基于二分查找或其他对数时间算法(不是对数),更不是指数时间算法(不是指数)。因此它是线性时间复杂度。

              函数

              (2019S1) Q39 - 40
              The function tests to see if the year passed as a parameter is a leap year.
              1. What is the time complexity, in terms of the logical complexity of the function above? You may assume arithmetic operations are constant time operations. a) O(1) – Constant b) O(log n) – Logarithmic c) O(n) – Linear d) O(n2) – Quadratic e) O(2n) – Exponential
              a
              这个函数检查一个给定的年份是否为闰年。函数由一系列的if-elif-else语句组成,不涉及任何循环或递归调用,每个语句的执行时间都是恒定的。因此,无论输入年份的大小如何,执行时间都保持不变。
              1. Assume each of the following sets of values are individually passed as parameters to the is_leap_year function. Which of these sets of values, would be the fewest number of inputs that would be required to test all logical paths in the function?
                1. 从最少的开始看 a) 2018, 2019, 2020. b) 1900, 2000, 2019, 2020. c) 1600, 1800, 1900, 2000, 2018, 2019, 2020. d) -400, -100, -5, -4, 0, 4, 5, 100, 400, a, aa, a4, a-4. e) None of the above.
              b
              • 一个能被400整除的年份(检查第一个if语句)
              • 一个能被100整除但不能被400整除的年份(检查elif语句)
              • 一个能被4整除但不能被100整除的年份(检查第二个elif语句)
              • 一个不能被4整除的年份(检查最后的else语句)
              a) 2018, 2019, 2020:没有能被100整除但不能被400整除的年份。 b) 1900, 2000, 2019, 2020:包含所有必要的测试年份。 c) 1600, 1800, 1900, 2000, 2018, 2019, 2020:也包含所有必要的测试年份,但比b选项多。 d) -400, -100, -5, -4, 0, 4, 5, 100, 400, a, aa, a4, a-4:包含无效和不相关的输入,而且预设条件是年份要大于0。 e) None of the above:不是正确选项,因为至少有一个选项包含了正确的测试集。
               
              Tutorial - COMP9024CQF - Python Lab Series3

              © 2023-2024

              chenoiLab - by Andy yang