跳到主要内容

Semester 1, 2024 Exam

Question 1
What is stored in x after only the following is entered into Python?

x = (7, 3, (6,)) + (9, (5))

A. (7, 3, 6, 9, 5)
B. (7, 3, (6,), 9, (5))
C. (7, 3, (6,), (9, (5)))
D. (7, 3, (6,), 9, 5)
E. Error

查看答案与解析

解析: 元组 + 运算会直接拼接,不展开内部元素,但是(5)会被解读为5

(7, 3, (6,)) + (9, (5)) → (7, 3, (6,), 9, 5)

答案:D. (7, 3, (6,), 9, 5)

Question 2
The following is a recursive function with a partially implemented base case. What should replace #sub?

def sum(xs: list[int]) -> int:
"""
>>> sum([1, 2, 3])
6
"""
(a, b) = #sub
if len(xs) == a:
return b
return xs[0] + sum(xs[1:])

A. (0, xs[0])
B. (1, xs[0])
C. (0, 1)
D. (0, 0)
E. None of the above

查看答案与解析

解析: 递归结束条件:列表为空 (len(xs) == 0) 时返回 0。

所以 (a, b) 应该是 (0, 0)。

答案:D. (0, 0)

Question 3
What is the value of x after the following code is executed?

x = [5, 9]
def f(xs: list, x) -> list:
xs.append(x)
return xs

x = f(x, 2) + x

A. [5, 9, 2]
B. [5, 9, 2, 5, 9]
C. [5, 9, 2, 5, 9, 2]
D. Error
E. None of the above

查看答案与解析

解析: f(x,2) 使得 x 变为 [5,9,2]

f(x,2) + x 是 [5,9,2] + [5,9,2] → [5,9,2,5,9,2]

答案:C. [5,9,2,5,9,2]

Question 4
What line of code should replace #sub in order to generate the window illustrated above?

import tkinter as tk
root = tk.Tk()
#sub
root.mainloop()

A. root.geometry("200x400")
B. root.geometry("200 x 400")
C. root.geometry("400x200")
D. root.geometry("400 x 200")
E. More than one of the above

查看答案与解析

解析: tkinter 的 .geometry() 方法要求字符串格式 "宽 x 高",且不能有空格。

"400x200" 是标准格式。

所以答案是:

答案:C. root.geometry("400x200")

Question 5
What is stored in x after only the following is entered into Python?

d = {'Brown': {'ID': 732, 'Orders': ['chisel', 'spanner']},
'Black': {'ID': 461, 'Orders': ['lathe', 'crowbar']}}
x = d.get('White').get('Orders')

A. ['chisel', 'spanner']
B. []
C. ['lathe', 'crowbar']
D. Error
E. None of the above

查看答案与解析

解析: d.get('White') 返回 None(因为'White'不存在)

None.get('Orders') 会触发 AttributeError。

题目要求:任何错误选择 Error。

答案:D. Error

Question 6
Suppose only the following lines have been executed:

xs = "champagne problems"
x = #sub

What should replace #sub so that 'e p' is assigned to x?
A. xs[8:10]
B. xs[8:11]
C. xs[-10:-8]
D. xs[-10:-7]
E. More than one of the above

查看答案与解析

解析: "champagne problems",下标是:

c h a m p a g n e   p r o b l e m s
0 1 2 3 4 5 6 7 8 9 10...

第 8 位是 'e',第 9 位是空格,10 位是'p'。

想要 "e p",需要取 8:11。

选项检查:

A. xs[8:10] = 'e ' ❌

B. xs[8:11] = 'e p' ✅

C. xs[-10:-8] = ' p' ❌

D. xs[-10:-7] = ' pr' ❌

所以只有 B 正确。

答案:B. xs[8:11]

Question 7
What is the value of the global variable a after the following code?

def f(x):
a = 3
x = x / a
return (a + x) % x

a = 9
f(a)

A. 0
B. 0.0
C. 3
D. 3.0
E. 9

查看答案与解析

解析: f(a) 是调用函数,内部 a=3 是局部变量,不影响外部。

外面的 a = 9 保持不变。

所以,全局 a 仍是 9。

答案:E. 9

Question 8
Given the following code:

x = input("Prompt: ")
y = input("Prompt: ")
print(f"x - y = {x - y}")

If the user types 7 then 3, what is printed?
A. x - y = 4
B. x - y = 7 - 3
C. 7 - 3 = 4
D. x - y = {x - y}
E. Error

查看答案与解析

解析: input() 返回字符串

"7" - "3" 直接做减法会出错,因为是字符串,不支持 - 运算。

会触发 TypeError。

答案:E. Error

Question 9
What is stored in y after only the following is entered into Python?

x = 'two \t \t pairs'
y = '\t'.join(x.split('\t'))

A. 'two \t pairs'
B. 'two \t \t pairs'
C. 'two\tpairs'
D. Error
E. None of the above

查看答案与解析

解析: x.split('\t') → ['two ', ' ', ' pairs']

再用 '\t'.join(...),重新用 tab 连接 → 'two \t \t pairs'

所以 y 仍是 'two \t \t pairs',与原字符串相同。

答案:B. 'two \t \t pairs'

Question 10
What replaces #sub to generate the image on the right?

import tkinter as tk

root = tk.Tk()
(s1, s2, s3, s4) = #sub

tk.Label(text="alice").pack(side=s1)
tk.Label(text="bob").pack(side=s2)
tk.Label(text="carol").pack(side=s3)
tk.Label(text="dilbert").pack(side=s4)

root.mainloop()

A. (tk.BOTTOM, tk.RIGHT, tk.TOP, tk.BOTTOM)
B. (tk.BOTTOM, tk.LEFT, tk.RIGHT, tk.TOP)
C. (tk.BOTTOM, tk.RIGHT, tk.LEFT, tk.BOTTOM)
D. (tk.BOTTOM, tk.LEFT, tk.LEFT, tk.LEFT)
E. None of the above

查看答案与解析

解析: 按照常规布局推测,若想依次排列:

alice: bottom

bob: left

carol: right

dilbert: top

符合顺序的是 B 选项。

答案:B. (tk.BOTTOM, tk.LEFT, tk.RIGHT, tk.TOP)

Question 11
What is the value of x after the following statements are evaluated?

x = 0
for y, z in enumerate([[1], [2]]):
x += 2 * y + z

A. 3
B. 5
C. 7
D. Error
E. None of the above

查看答案与解析

解析: enumerate([[1],[2]]) 生成 (0, [1]), (1, [2])

在循环中,z 是一个列表 [1] 或 [2]

2*y + z → int + list,类型不兼容,会直接报 TypeError

答案:D. Error

Question 12
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 in [])
E. More than one of the above

查看答案与解析

解析: 空列表 xs = []

not xs → True

bool(not xs) → True

其他选项:

bool(xs) → False

bool(len(xs)) → bool(0) → False

xs in [] → 错误,判断一个列表是不是列表元素,不是。

所以,只有 A 正确。

答案:A. bool(not xs)

Question 13
Suppose we want to define a name for maximum volume that is intended to be private. Which name is most appropriate?
A. maximum_volume
B. MaximumVolume
C. _maximum_volume
D. MAXIMUM_VOLUME
E. maximumValue

查看答案与解析

解析: 私有变量通常以单下划线 _ 开头。

name 双下划线包围的是 特殊方法,比如 init

MAXIMUM_VOLUME 是常量风格。

所以,正确答案是 _maximum_volume。

答案:C. _maximum_volume

Question 15
What is the value of x after only the following code is executed?

x = 5.1 + 24.2 // 6 ** 2

A. 5
B. 5.1
C. x
D. 21
E. 21.1

查看答案与解析

解析: 运算符优先级:

** 指数运算最高,先算 6 ** 2 = 36

24.2 // 36 进行地板除法:

24.2 // 36 结果是 0.0

再加上 5.1:

5.1 + 0.0 = 5.1

所以最终 x = 5.1

答案:B. 5.1

Question 16
What is the value of x after only the following code is executed?

x = 1 // 4 * 'drake'

A. '' (the empty string)
B. ' ' (a space)
C. 'd'
D. 'drake'
E. Error

查看答案与解析

解析: 1 // 4 是整数除法,结果是 0

0 * 'drake' → 字符串重复 0 次 → 结果是 ''(空字符串)

答案:A. '' (the empty string)

Question 17
After starting Python interpreter, what happens when entering this code?

if [] and y:
y = 0
else:
y = 1

What error (if any) does this code raise?
A. NameError
B. IndexError
C. TypeError
D. SyntaxError
E. This is valid Python code

查看答案与解析

解析: [] 是空列表,布尔值是 False

False and y → False,短路了,不会去访问 y

所以不会因为 y 未定义而报错。

正常进入 else 分支,执行 y = 1

整个代码是有效的。

答案:E. This is valid Python code

Question 18
Consider the following function:

def foo(xs: list[int], ys: dict) -> bool:
""" Precondition: len(xs) > 0 """
for x in xs:
if not x in ys:
return True
return False

What best describes the behaviour of foo provided it is invoked with all preconditions satisfied?
A. foo always returns True.
B. foo always returns False.
C. foo returns False only when every element of xs is a key of ys.
D. foo returns True only when there is an element of xs that is a value of ys.
E. foo always throws an Error.

查看答案与解析

解析: for x in xs 遍历 xs 中的每个元素

如果某个元素不在 ys 的 key 中,就返回 True

如果所有元素都在 ys 的 key 中,最后返回 False

因此:

当 每一个元素都是字典的 key 时,返回 False

否则返回 True

对应选项:

答案:C. foo returns False only when every element of xs is a key of ys.

Question 19
Which of the following statements is true?
A. Lists are mutable but dictionaries are immutable.
B. User defined classes are by default immutable.
C. Values and keys in dictionaries must both be immutable.
D. Strings, integers, floats, booleans and lists are all immutable.
E. None of the above.

查看答案与解析

解析: 列表(list)和字典(dict)**都是可变(mutable)**的。

自定义类默认也是可变的,除非特别定义成不可变。

字典的 key 必须是不可变的(比如字符串、元组),但 value 可以是可变的。

字符串、整数、浮点数、布尔值是不可变的,但列表是可变的。

所以,A、B、C、D 都不正确,正确选项是:

答案:E. None of the above

Question 20
What is the value of z after executing the following code?

xss = ['basket', 'bird', 'balloon']
ys = ['ball']
z = [ys[0] in xs and ys[1] in xs for xs in xss]

A. [True]
B. [False]
C. [True, False, True]
D. [True, True, True]
E. Error

查看答案与解析

解析: ys[0] 是 'ball'

但是 ys 只有一个元素,访问 ys[1] 会触发 IndexError。

所以代码执行时报错。

答案:E. Error

Question 21
What is the value of y after the following code?

x = [0, [1, 2], 3]
y = x[-2, 1]

A. 0
B. 1
C. 2
D. 3
E. Error

查看答案与解析

解析: x[-2] 是 [1, 2]

但是 x[-2, 1] 是用两个索引,Python 的 list 不支持这种写法(应该是先取 x[-2] 再取[1])

因为 x[-2, 1] 是非法索引,会直接触发 TypeError: list indices must be integers or slices, not tuple

所以会报错。

答案:E. Error

Question 22
Consider the following function:

def foo(xs: str) -> None:
for x in xs:
with open('file.txt', 'w') as f:
f.write(x)
return

After calling foo, what can be the contents of file.txt?
A. aaaa
B. wawa
C. awwaww
D. All of them
E. None of the above

查看答案与解析

解析: open('file.txt', 'w') 在每次循环都会覆盖文件内容(不是追加)

每次只会保存最后一次写入的字符。

所以最终 file.txt 只保存了最后一次写入的单个字符。

因此,不可能出现 aaaa、wawa 或 awwaww 这样的内容。

答案:E. None of the above

Question 23
Consider the function definition below. What would you expect lcs(" ", "eras") to return?

def lcs(xs: str, ys: str) -> str:
""" Return the longest substring that both xs and ys have in common. """

A. "" (empty string)
B. " " (single space)
C. "eras"
D. Error
E. None of the above

查看答案与解析

解析: lcs 取两个字符串的最长公共子串。

" "(一个空格)和 "eras" 没有任何公共子串。

所以返回的是空字符串 ""。

答案:A. "" (empty string)

Question 24
What error (if any) will the following code produce when executed by Python?

def foo(x: int, xs: list[int]) -> bool:
return x in xs

foo('', ' ')

A. NameError
B. IndexError
C. TypeError
D. SyntaxError
E. This is valid Python code

查看答案与解析

解析: foo 定义的参数是 int 和 list[int]

调用时传入 ''(字符串)和 ' '(字符串)

Python 本身不会强制类型提示,但是:

'' in ' '(字符串中查找子串)是合法的,结果是 True

所以虽然类型不匹配,但是不会报错。

答案:E. This is valid Python code

Question 25
What is the value of x after only the following has been evaluated?

x = "goodbye".replace("ood", "ello")

A. "gellobye"
B. "goodbye"
C. "hellobye"
D. None
E. Error

查看答案与解析

解析: .replace("ood", "ello") 把第一个出现的 "ood" 替换成 "ello"

"goodbye" → "gellobye"

答案:A. "gellobye"

Question 26
What exception should be used at <Error> to complete the function?

def get_value(dictionary: dict, key: str) -> int:
"""
Retrieves the value associated with the provided key in the dictionary.
Continues prompting the user until a valid key is entered.
"""
try:
return dictionary[key]
except <Error>:
return get_value(dictionary, input("Enter another key: "))

A. NameError
B. IndexError
C. TypeError
D. DictError
E. KeyError

查看答案与解析

解析: 访问字典中不存在的 key 时,抛出 KeyError

所以应该捕获 KeyError。

答案:E. KeyError

Question 27
For the following function:

def r(x: int, y: int) -> int:
if x == 0:
return x * y
return r(x-5, y) + y

What will r(4, 2) return?
A. 0
B. 4
C. 8
D. 10
E. RecursionError

查看答案与解析

解析: r(4,2):

x=4 ≠ 0,调用 r(-1,2) + 2

r(-1,2):

x=-1 ≠ 0,调用 r(-6,2) + 2

r(-6,2):

无限向负数递归,没有结束条件。

最终导致递归深度超限,抛出 RecursionError。

答案:E. RecursionError

Question 28
What does z get assigned assuming 23 is the two-digit number entered?

x = input("Input two digit number: ")
y = int(x)
z = y[0]

A. 2
B. 23
C. None
D. Error
E. None of the above

查看答案与解析

解析: input() 返回字符串,比如 "23"

y = int(x) 把字符串转成整数 23

z = y[0]:

错误!整数 y=23 不能用索引 [0]。

会报错 TypeError: 'int' object is not subscriptable

所以结果是 Error。

答案:D. Error

Question 29
What is the value of z after running the following code?

xs = ['a', (3, 4), {1: 'b'}]
ys = xs.copy()
ys[2] = {2: 'c'}
z = xs[2][1]

A. 'a'
B. 'b'
C. 'c'
D. Error
E. None of the above

查看答案与解析

解析: xs 是原列表:["a", (3,4), {1:"b"`}]

ys = xs.copy() 是浅拷贝(复制列表对象,但元素本身仍指向同一对象)

ys[2] = {2:'c'} 只是让 ys 中第三个元素指向新字典 {2: 'c'},不会影响原来的 xs

所以 xs[2] 仍然是 {1: 'b'}

xs[2][1] 取 key=1,对应 value 是 'b'

答案:B. 'b'

Question 30
What is the purpose of "setter" methods as they pertain to objects?
A. They are used to change the value of a private variable.
B. They are used to retrieve the value of a private variable.
C. They allow private variables to be shared among multiple instances of the same class.
D. They are used to read data from files.
E. More than one of the above.

查看答案与解析

解析: Setter 方法是对象中的一个专门方法,用来**设置或更改私有变量(通常是以 _ 开头的变量)**的值。

Getter 则是取值。

与文件操作、实例共享无关。

答案:A. They are used to change the value of a private variable.

class A(object):
def __init__(self, x):
self._x = 2 * x

def f(self, x):
return self.g(x) + 2

def g(self, x):
return x - 1

class B(A):
def g(self, y):
return self._x + y

class C(B):
def __init__(self, x, y):
super().__init__(x)
self._y = y + 2

def f(self, x):
return self._x + self._y

class D(B):
def __init__(self, x, y):
super().__init__(x)
self._x += y
self._y = y + 2

def f(self, y):
return self._y + y

def g(self, x):
return super().g(x) - x

a = A(1)
b = B(2)
c = C(3, 4)
d = D(5, 6)

Question 31
What does a.f(4) return?

查看答案与解析

解析: a 是 A(1),即 self._x = 2*1 = 2

a.f(4) 调用:

self.g(4) + 2

A.g(4) 是 4 - 1 = 3

所以 f(4) 返回 3 + 2 = 5

答案:5

Question 32
What does b.g(3) return?

查看答案与解析

解析: b 是 B(2),self._x = 2*2 = 4

B.g(3) 定义是:return self._x + y

所以返回:4 + 3 = 7

答案:7

Question 33
What does c.f(2) return?

查看答案与解析

解析: c 是 C(3, 4)

self._x = 2*3 = 6

self._y = 4 + 2 = 6

c.f(2) 调用 return self._x + self._y

返回 6 + 6 = 12

答案:12

Question 34
What does d.f(1) return?

查看答案与解析

解析: d 是 D(5,6)

self._x = 2*5 =10,再加上 6 变成 self._x = 16

self._y = 6 + 2 = 8

d.f(1) 调用 return self._y + y

返回 8 + 1 = 9

答案:9

Question 35
What does d.g(0) return?

查看答案与解析

解析: d.g(0) 重写了 g 方法:return super().g(x) - x

调用 super().g(0):

super() 是 B

B.g(0) 是 self._x + y,即 16 + 0 = 16

然后 16 - 0 = 16

答案:16

Question 36
Implement the following function according to its specification:

def foo(xs: str, ys: str) -> bool:
"""
Given two strings xs and ys, return true only when xs is equal
to ys when typed into an empty text editor interpreting '!' as
typing a backspace character.

For example:
>>> foo("ab!c", "ac")
True
because "ab!c" becomes "ac" when typed.

>>> foo("ab!!", "ab")
False
because "ab!!" becomes "" (empty string) when typed.

>>> foo("a!c", "c")
True
because "a!c" becomes "c" when typed.

Note that backspacing on the empty string produces the empty string.
"""
查看参考答案与解析

解析: 根据题意:

! 表示退格,删掉当前已有的最后一个字符(如果有的话)

要模拟键盘输入的行为

最后比较模拟后的 xs 和 ys 是否相同

常规做法是:用一个栈(list)模拟编辑器输入。

示范参考实现:

def process(s: str) -> str:
result = []
for c in s:
if c == '!':
if result:
result.pop()
else:
result.append(c)
return ''.join(result)

def foo(xs: str, ys: str) -> bool:
return process(xs) == ys

🔵 思路总结:

写一个 process 辅助函数处理退格

用 list 当栈,正常字符就 append,遇到 ! 就 pop

最后把 list 合成字符串

再比较 process(xs) 和 ys 是否一致

✅ 这样 foo("ab!c", "ac")、foo("ab!!", "ab")、foo("a!c", "c") 都能正确返回。