Semester 2, 2024 Exam
Question 1
What does the following arithmetic expression evaluate to in Python?
2 ** 2 % 4 - 2
A. 2
B. -2
C. 1
D. -1
E. None of the above
查看答案与解析
解析:
运算符优先级如下:
*(指数) > %(取余) > (减法)
所以按顺序计算:
2 ** 2 = 4
4 % 4 = 0
0 - 2 = -2
答案:B. -2
Question 2
What is stored in x when only the following is executed by Python?
x = len("\n\t23\t\n")
A. 10
B. 6
C. 2
D. It depends on the number of spaces in a tab.
E. None of the above
查看答案与解析
解析:
字符串内容为 \n\t23\t\n
\n是换行,占 1 个字符\t是制表符,占 1 个字符'2'和'3'各占 1 个字符- 共两个
\n,两个\t,两个数字 → 共 6 个字符
答案:B. 6
Question 3
After starting Python interpreter, what error (if any) does this code raise?
if True or x:
x = 1
else:
x = 0
A. TypeError
B. ValueError
C. NameError
D. SyntaxError
E. This is valid Python code.
查看答案与解析
解析:
虽然 x 未定义,但 if True or x 中的 True 足以使条件成立,Python 是"短路求值"(short-circuiting),因此 x 不会在 or 表达式中被访问,也不会触发错误。
答案:E. This is valid Python code.
Question 4
What is the value of x after only the following code is executed?
x = 'Hello World' - 2 * 'Hello World'
A. '' (the empty string)
B. Hello WorldHello World
C. Hello World
D. Error
E. None of the above
查看答案与解析
解析:
Python 中字符串不支持减法运算 -,这是非法操作,会触发 TypeError。
答案:D. Error
Question 5
What is stored in y after only the following is entered into Python?
y = ':'.join('hands \t many'.split('\t'))
A. hands:many
B. hands : many
C. hands: many
D. Error
E. None of the above
查看答案与解析
解析:
'hands \t many'中的\t是 tab,字符串变为'hands<TAB>many'.split('\t')将其分为:['hands ', ' many']- 然后用
':'连接:'hands : many'(注意空格保留)
答案:C. hands: many
Question 6
The following is a recursive function with a partially implemented base case; it counts the number of elements in a list. What should we replace #sub with to complete this function?
def count(xs: list[int]) -> int:
(a, b) = #sub
if len(xs) == a:
return b
return 1 + count(xs[1:])
A. (1, 1)
B. (0, 0)
C. (0, 1)
D. (1, 0)
E. None of the above
查看答案与解析
解析:
我们需要填充 base case 的 (a, b),使得当 xs 为空时返回 0,即 len(xs) == 0 时返回 0。
所以应该是:(0, 0)
答案:B. (0, 0)
Question 7
Given the following code, if the user types 5 at the first prompt then 2 at the second prompt, what is printed?
x = input("Prompt: ")
y = input("Prompt: ")
print(f"x + y = {int(x + y)}")
A. x + y = 7
B. x + y = '7'
C. x + y = 52
D. x + y = '52'
E. Error
查看答案与解析
解析:
input()返回字符串 →x = "5",y = "2"x + y是字符串拼接 →"5" + "2" = "52"int("52") = 52- 输出为:
x + y = 52
答案:C. x + y = 52
Question 8
What is stored in y after only the following code is executed?
def g(x, z):
x.append(z)
return x
y = ['a', 'b']
g(y, 'c').append(g(y.copy(), 'c'))
A. ['a', 'b', 'c']
B. ['a', 'b', 'c', 'c']
C. ['a', 'b', 'c', 'a', 'b', 'c']
D. ['a', 'b', 'c', ['a', 'b', 'c', 'c']]
E. Error
查看答案与解析
解析:
- 初始
y = ['a', 'b'] g(y, 'c')修改了 y:变为['a', 'b', 'c'].append(g(y.copy(), 'c'))y.copy()是['a', 'b', 'c']的副本g(['a', 'b', 'c'], 'c')→ 返回['a', 'b', 'c', 'c']- 所以 y 最终变为:
['a', 'b', 'c', ['a', 'b', 'c', 'c']]
答案:D. ['a', 'b', 'c', ['a', 'b', 'c', 'c']]
Question 9
Suppose some code has been styled in accordance with the style guide used in this course. What can be deduced about the name FOO_BAR?
A. class name
B. constant variable
C. method
D. private variable
E. None of the above
查看答案与解析
解析:
全大写 + 下划线风格在 Python 中通常表示 常量。
答案:B. constant variable
Question 10
Suppose the following function definition has been made. What does foo(-1, 1) return?
def foo(x, y):
if x - y == 0:
return x
return foo(x-1, y)
A. 0
B. 1
C. -1
D. -2
E. Error
查看答案与解析
解析:
- 初始
x = -1,y = 1 -1 - 1 = -2 ≠ 0→ 递归:foo(-2, 1)- 一直减小 x,没有结束条件
- 会无限递归直到最大递归深度,最终触发
RecursionError
答案:E. Error
Question 11
What is the value of x after only the following has been evaluated?
x = "Hello Hello".find("Hello")
A. 0
B. 6
C. -1
D. None
E. ValueError
查看答案与解析
解析:
str.find()返回子串第一次出现的位置"Hello Hello"中"Hello"首次出现的索引是 0
答案:A. 0
Question 12
What exception should be used to replace <e> at line 8 to complete the function according to specification?
def get_element(xs: list[int], index: int) -> int:
try:
return xs[index]
except <e>:
return get_element(xs, int(input("Enter a valid index: ")))
A. TypeError
B. NameError
C. IndexError
D. KeyError
E. ValueError
查看答案与解析
解析:
xs[index]会在索引越界时抛出IndexError,应捕获这个异常
答案:C. IndexError
Question 13
What is the value of b after the following code is executed?
def f(x):
a = 5
x = x / a
return a+x
a = 10
b = f(a)
A. 7
B. 7.0
C. 15.0
D. 15
E. Error
查看答案与解析
解析:
f(10)→a = 5(函数内部作用域)x = 10 / 5 = 2.0- 返回
5 + 2.0 = 7.0
答案:B. 7.0
Question 14
What replaces #sub1 and #sub2 in the following code to generate the image?
import tkinter as tk
root = tk.Tk()
s1 = #sub1
s2 = #sub2
alice = tk.Label(root, text="alice")
alice.pack(side = s1[0], expand = s1[1])
bob = tk.Label(root, text="bob")
bob.pack(side = s2[0], expand = s2[1])
root.mainloop()
A. sub1 = (tk.RIGHT, tk.FALSE), sub2 = (tk.LEFT, tk.TRUE)
B. sub1 = (tk.RIGHT, tk.TRUE), sub2 = (tk.LEFT, tk.FALSE)
C. sub1 = (tk.LEFT, tk.FALSE), sub2 = (tk.RIGHT, tk.TRUE)
D. sub1 = (tk.LEFT, tk.TRUE), sub2 = (tk.RIGHT, tk.FALSE)
E. None of the above
查看答案与解析
解析:
- 题目要求 alice 在左侧展开,bob 在右侧不展开
side=tk.LEFT,expand=True:左侧可拉伸side=tk.RIGHT,expand=False:右侧不拉伸
答案:D. sub1 = (tk.LEFT, tk.TRUE), sub2 = (tk.RIGHT, tk.FALSE)
Question 15
What is the value of y after the following statements are evaluated?
x = ['hello', 'HELLO', 'world', 'WORLD']
y = x[-1][-5]
A. 'd'
B. 'D'
C. 'w'
D. 'W'
E. Error
查看答案与解析
解析:
x[-1] = 'WORLD''WORLD'[-5]即索引 0 →'W'
答案:D. 'W'
Question 16
Consider the function product defined below that multiplies two numbers. What is the value of x?
def product(num1: int, num2: int):
print(2 * num1)
return num1 * num2
return
x = product(3, 4.0)
A. 6
B. 12.0
C. 12
D. None
E. Error
查看答案与解析
解析:
print(2 * 3)输出 6return 3 * 4.0 = 12.0- 第二个
return是多余的,不影响执行 - 所以
x = 12.0
答案:B. 12.0
Question 17
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("300x100")
B. root.geometry(300x100)
C. root.geometry("100x300")
D. root.geometry(100x300)
E. None of the above
查看答案与解析
解析:
- tkinter 的
.geometry()方法必须传入一个字符串 - 题目图像显示窗口宽 300、高 100
- 正确的格式为
"宽x高"
答案:A. root.geometry("300x100")
Question 18
What is the purpose of "setter" methods as they pertain to objects?
A. They are used to retrieve the value of a private variable.
B. They are used to change the value of a private variable.
C. They change a private variable to a public one and vice-versa.
D. They ensure that all private variables have the correct type.
E. None of the above.
查看答案与解析
解析:
- setter 是设置器,专门用于设置 私有属性(private variable) 的值
- 即使属性名带下划线
_x,也可以通过 setter 控制其修改方式和校验逻辑
答案:B. They are used to change the value of a private variable.
Question 19
What is stored in x after only the following is entered into Python?
x = (1, 2) + (2, 3)
A. (1, 2, 3)
B. (3, 5)
C. (1, 2, 2, 3)
D. [(1, 2), (2, 3)]
E. Error
查看答案与解析
解析:
元组相加会拼接 →
(1, 2) + (2, 3)→(1, 2, 2, 3)
答案:C. (1, 2, 2, 3)
Question 20
What error (if any) will the following code produce when executed by Python?
def concatenate(xs: list[int], ys: list[int]) -> list[int]:
return xs + ys
concatenate(' ', '2a')
A. SyntaxError
B. TypeError
C. NameError
D. ValueError
E. This is valid Python code.
查看答案与解析
解析:
xs和ys都期望是list[int],但传入的是字符串' '和'2a'- 字符串
+运算合法 →' ' + '2a' = ' 2a' - 然而函数签名期望
list[int],但 Python 不会强制类型检查 → 运行不会报错
答案:E. This is valid Python code.
Question 21
What is the value of ys after only the following has been evaluated?
z = lambda x: x ** 2
xs = [3, 4, 5, 6]
ys = [z(x) for x in xs if x < 5]
A. [3, 4, 5]
B. [9, 16, 25]
C. [3, 4]
D. [9, 16]
E. Error
查看答案与解析
解析:
if x < 5→ 选出 3 和 4z(3) = 9,z(4) = 16- 所以
ys = [9, 16]
答案:D. [9, 16]
Question 22
What is the value of x after running the following code?
cs = 'abc'
for k, c in enumerate(cs):
x = 2*k + c
A. 'abbcccc'
B. 'abcd'
C. 'aabbbbcccccccc'
D. Error
E. None of the above
查看答案与解析
解析:
enumerate(cs):依次为(0, 'a'),(1, 'b'),(2, 'c')2*k + c→int + str会导致TypeError- 例如:
2*0 + 'a'=0 + 'a'→ 报错
答案:D. Error
Question 23
After the assignment s1 = "Hello World" which of the following statements assigns "o W" to s2?
A. s2 = s1[4:7]
B. s2 = s1[4:-4]
C. s2 = s1[-7:-4]
D. All of the above
E. None of the above
查看答案与解析
解析:
"Hello World" 索引: 0123456789 10
"o W"在索引位置 4~6(不含 7)
逐一验证:
- A.
s1[4:7]→'o W'✅ - B.
s1[4:-4]→'o W'✅,-4 表示倒数第 4 个字符,即'r' - C.
s1[-7:-4]→'o W'✅,倒数第 7 个到倒数第 5 个字符
答案:D. All of the above
Question 24
How many of the following expressions are equivalent to yss?
xss = ['abcdef', 'ABCDEF', 'ghijkl']
yss = ['def', 'DEF']
- [xs[-3:] for xs in xss[0:2]]
- [xs[3:] for xs in xss[0:-1]]
- [xs[-3:] for xs in xss[-3:-1]]
- [xs[3:] for xs in xss[-3:2]]
A. 0
B. 1
C. 2
D. 3
E. 4
查看答案与解析
解析:
分析每个表达式:
-
[xs[-3:] for xs in xss[0:2]]→[xs[-3:] for xs in ['abcdef', 'ABCDEF']]→['def', 'DEF']✅ -
[xs[3:] for xs in xss[0:-1]]→[xs[3:] for xs in ['abcdef', 'ABCDEF']]→['def', 'DEF']✅ -
[xs[-3:] for xs in xss[-3:-1]]→[xs[-3:] for xs in ['abcdef', 'ABCDEF']]→['def', 'DEF']✅ -
[xs[3:] for xs in xss[-3:2]]→[xs[3:] for xs in ['abcdef', 'ABCDEF']]→['def', 'DEF']✅
所以有 4 个表达式等价于 yss。
答案:E. 4
Question 25
How many stars (*) are in output.txt after calling foo without generating an error?
def foo() -> None:
xs = ['*', '**', '***']
for x in xs:
with open("output.txt", "w") as f:
f.write(2*x)
A. 0
B. 3
C. 6
D. 12
E. Impossible to deduce without knowing the initial contents of output.txt.
查看答案与解析
解析:
- 每次
open(..., "w")都会覆盖文件内容 - 所以最终只保留最后一次写入:
2 * '***' = '******' - 有 6 个星号
答案:C. 6
Question 26
What is stored in y after only the following code is executed?
def foo(xs: list[str]) -> list[str]:
if xs:
xs.append(" ")
return xs
return []
y = foo([""])
A. ["", " "]
B. [" "]
C. [""]
D. []
E. Error
查看答案与解析
解析:
xs = [""],非空列表,满足if xs:条件- 然后执行
xs.append(" ")→["", " "] - 返回这个列表
答案:A. ["", " "]
Question 27
What is the best description of the behaviour of the following function?
def bar(d1: dict, d2: dict) -> bool:
for x in d1:
if x not in d2 or d1[x] != d2[x]:
return False
return True
A. bar only returns True when all keys in d2 exist in d1 and False otherwise.
B. bar only returns True when all key-value pairs in d1 exist in d2 and False otherwise.
C. bar always returns False.
D. bar always returns True.
E. bar always throws errors.
查看答案与解析
解析:
这段代码的含义是:
d1中的所有 key 都存在于d2且值相同,才返回 True- 即:判断
d1是否是d2的子集(在 key-value 级别)
答案:B. bar only returns True when all key-value pairs in d1 exist in d2 and False otherwise.
Question 28
What is the value of xs after running the following code?
xs = [['12'], {1: '1'}]
xs[1] = {xs[0]: '2'}
A. [['12'], {['12']: '2'}]
B. [['12'], {['1']: '2'}]
C. [['12'], {'12': '2'}]
D. Error
E. None of the above
查看答案与解析
解析:
xs[0] = ['12']是列表,不可哈希(unhashable),不能作为 dict 的 keydict[[list] : value]会触发TypeError
答案:D. Error
Question 29
What is the value of ys after running the following code?
xs = 'hello'
ys = xs
ys[0] = 'H'
A. 'hello'
B. 'Hello'
C. 'H'
D. Error
E. None of the above
查看答案与解析
解析:
字符串在 Python 中是 不可变的(immutable),不能通过索引赋值
→ 报错 TypeError: 'str' object does not support item assignment
答案:D. Error
Question 30
Which statement is false?
A. Type-hints are not enforced by Python.
B. Python prohibits the user from changing constant variables.
C. Functions can be defined inside of functions.
D. Every for loop can be written as a while loop.
E. None of the above.
查看答案与解析
解析:
A. Type-hints are not enforced by Python. ✅ True
B. Python prohibits the user from changing constant variables. ❌ Python 没有真正的常量机制,只是风格约定(如全大写)
C. Functions can be defined inside of functions. ✅ True
D. Every for loop can be written as a while loop. ✅ True
E. None of the above. ❌ 因为 B 是错的
答案:B. Python prohibits the user from changing constant variables.
The next five questions refer to the following class definitions.
class A(object):
def __init__(self, x):
self._x = 2 * x
def f(self, x):
return x + self._x
def g(self, x):
return 2 * self.f(x) - x
class B(A):
def f(self, x):
return self._x - x
class C(B):
def __init__(self, x, y):
super().__init__(x)
self._y = y + 2
class D(B):
def __init__(self, x, y):
super().__init__(x)
self._x += 2 * y
self._y = y
def f(self, x):
return self._y + x
def g(self, x):
return super().g(x) - x
a = A(1)
b = B(2)
c = C(1, 1)
d = D(2, 1)
Question 31. [1 mark]
What does a.f(2) return?
查看答案与解析
解析:
a = A(1)→self._x = 2 * 1 = 2a.f(2)→return 2 + self._x = 2 + 2 = 4
答案:4
Question 32. [1 mark]
What does b.g(1) return?
查看答案与解析
解析:
b = B(2)→self._x = 2 * 2 = 4b.g(1)→return 2 * self.f(1) - 1b.f(1)→return self._x - 1 = 4 - 1 = 3(使用B类的f方法)2 * 3 - 1 = 5
答案:5
Question 33. [1 mark]
What does c.f(3) return?
查看答案与解析
解析:
c = C(1, 1)→ 调用super().__init__(1)→self._x = 2 * 1 = 2self._y = 1 + 2 = 3c.f(3)→ 使用继承自B类的f方法 →return self._x - 3 = 2 - 3 = -1
答案:-1
Question 34. [1 mark]
What does d.f(3) return?
查看答案与解析
解析:
d = D(2, 1)→ 调用super().__init__(2)→self._x = 2 * 2 = 4self._x += 2 * 1 = 4 + 2 = 6self._y = 1d.f(3)→ 使用D类自己的f方法 →return self._y + 3 = 1 + 3 = 4
答案:4
Question 35. [1 mark]
What does d.g(1) return?
查看答案与解析
解析:
d.g(1)→ 使用D类的g方法 →return super().g(1) - 1super().g(1)→ 调用A类的g方法 →return 2 * self.f(1) - 1self.f(1)→ 使用D类的f方法 →return self._y + 1 = 1 + 1 = 22 * 2 - 1 = 3- 最终:
3 - 1 = 2
答案:2
Question 36. [5 marks]
Implement the following function according to its specification. Do not include a docstring.
def remove_adjacent_pairs(cs: str) -> str:
"""
Given a string cs, return the string obtained after removing all adjacent pairs of
duplicate characters from cs. This process should be repeated until no adjacent
duplicates remain.
Parameters:
cs: A string that needs to be processed.
Return:
A modified version of cs where all adjacent pairs of duplicate characters have
been removed.
Examples:
>>> remove_adjacent_pairs("abbaca")
'ca'
because "abbaca" -> "aaca" -> "ca" after removing adjacent pairs.
>>> remove_adjacent_pairs("aaac")
'ac'
because "aaac" -> "ac" after removing one pair of "a"s.
>>> remove_adjacent_pairs("azxxzy")
'ay'
because "azxxzy" -> "azzy" -> "ay" after removing adjacent pairs.
>>> remove_adjacent_pairs("aabbcc")
''
because "aabbcc" -> "" after removing all adjacent pairs.
Note that after each removal of adjacent duplicated pairs, the process continues
on the resulting string until no more adjacent duplicated pairs exist.
"""
查看参考答案
解析:
可以使用栈(stack)的思想来解决这个问题:
def remove_adjacent_pairs(cs: str) -> str:
stack = []
for char in cs:
if stack and stack[-1] == char:
stack.pop() # 移除相邻的重复字符
else:
stack.append(char)
return ''.join(stack)