Semester 2, 2022 Exam
Question 1
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 2
What is the value of ans after running the following code?
xs = [3, 5, 7, 9]
ans = 0
for x in xs:
ans += x // 2
A. 10
B. 10.5
C. 11
D. 11.5
E. 12
查看答案与解析
解析:
// 是整数除法,向下取整。
3 // 2 = 1
5 // 2 = 2
7 // 2 = 3
9 // 2 = 4
总和:1 + 2 + 3 + 4 = 10
答案:A. 10
Question 3
Consider the following function.
def foo(xs: list[int], ys: dict) -> bool:
for x in xs:
if not x in ys:
return False
return True
What statement best describes the behaviour of foo?
A. foo always returns True.
B. foo always returns False.
C. foo returns True when every element of xs is a value of ys.
D. foo returns True when every element of xs is a key of ys.
E. None of the above.
查看答案与解析
解析:
if not x in ys 检查 x 是否是 ys 的键。
所以只有当 xs 中所有元素都是 ys 的键时,才返回 True。
答案:D. foo returns True when every element of xs is a key of ys.
Question 4
Which option will throw an IndexError in the following code when replacing #sub?
xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#sub
A. xs[len(xs)]
B. xs[1-len(xs)]
C. xs[len(xs)-1]
D. xs[-1-len(xs)]
E. More than one of the above.
查看答案与解析
解析:
len(xs) = 10
A: xs[10] 超出索引范围
B: xs[-9] 合法
C: xs[9] 合法
D: xs[-11] 超出索引范围
所以 A 和 D 都会抛出 IndexError。
答案:E. More than one of the above.
Question 5
Supposing Pep 8 guidelines have been followed what can be deduced about the name FooBar?
FooBar is a...
A. global variable.
B. constant.
C. class name.
D. method.
E. None of the above.
查看答案与解析
解析:
PEP 8 规定:
- 类名使用 PascalCase(如
FooBar) - 变量名使用 snake_case(如
foo_bar) - 常量使用 UPPER_CASE(如
FOO_BAR) - 方法名使用 snake_case(如
foo_bar)
答案:C. class name.
Question 6
Which option will throw an IndexError in the following code when replacing #sub?
xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#sub
A. xs[len(xs)]
B. xs[1-len(xs)]
C. xs[len(xs)-1]
D. xs[-1-len(xs)]
E. More than one of the above.
查看答案与解析
解析:
len(xs) = 10
A: xs[10] 超出索引范围
B: xs[-9] 合法
C: xs[9] 合法
D: xs[-11] 超出索引范围
所以 A 和 D 都会抛出 IndexError。
答案:E. More than one of the above.
Question 7
What value gets assigned to x?
x = 35 % 2 * 5 * 2
A. 0
B. 20
C. 70
D. 140
E. None of the above.
查看答案与解析
解析:
运算顺序:
- 35 % 2 = 1
- 1 * 5 = 5
- 5 * 2 = 10
答案:E. None of the above.
Question 8
How many of the following expressions evaluate to True? Note: Expressions that throw errors do not evaluate to True.
bool(not [] and "hello")
bool(True or 1/0)
bool(" ")
bool(1 > False)
A. 0
B. 1
C. 2
D. 3
E. 4
查看答案与解析
解析:
not []是True,"hello"是True,所以True and True = True✅True or ...短路,直接返回True✅- 非空字符串为
True✅ 1 > False即1 > 0为True✅
答案:E. 4
Question 9
What is the value of ans after executing the following.
ans = 0
for x in range(10):
if x == 0 or 1 or 9 or 10:
ans += 1
A. 0
B. 3
C. 4
D. 10
E. None of the above.
查看答案与解析
解析:
if x == 0 or 1 or 9 or 10 实际理解为 (x == 0) or (1) or (9) or (10),由于非零数字在布尔上下文中为 True,所以条件永远为 True。
range(10) 是 0 到 9,共 10 个数,全部满足条件,每次 ans += 1。
答案:D. 10
Question 10
What is the value of x after executing the following.
x = (1, 2, 3) + (4, 5, 6)
A. 21
B. (5, 7, 9)
C. (1, 2, 3, 4, 5, 6)
D. Error
E. None of the above.
查看答案与解析
解析:
元组加法是拼接,所以 (1, 2, 3) + (4, 5, 6) = (1, 2, 3, 4, 5, 6)。
答案:C. (1, 2, 3, 4, 5, 6)
Question 11
The following is a recursive function with a partially implemented base case; it computes the product a list of numbers. What should we replace #sub with to complete this function?
def product(xs: list[int]) -> int:
"""
>>> product([1, 2, 3])
6
"""
(a, b) = #sub
if len(xs) == a:
return b
return xs[0] * product(xs[1:])
A. (0, xs[0])
B. (1, xs[0])
C. (0, 1)
D. (1, 1)
E. None of the above.
查看答案与解析
解析:
当列表为空时,应返回 1(乘法的单位元)。
所以 (a, b) 应该是 (0, 1)。
答案:C. (0, 1)
Question 12
What type of error is thrown by executing the following code?
def foo(x: int, y: int) -> int:
"""
>>> foo(2, 3)
6
"""
return x*y
ans = foo("oi", 3)
A. TypeError
B. NameError
C. ValueError
D. IndexError
E. This is valid Python code.
查看答案与解析
解析:
foo("oi", 3) 传入的是 str,而函数预期是 int,会抛出 TypeError。
答案:A. TypeError
Question 13
What is the value of ans after running the following code.
def foo(xs: list):
if not xs:
return [[]]
else:
ys = foo(xs[1:])
x = xs[0]
return [y + [x] for y in ys] + ys
ans = foo([1, 2, 3])
A. [[], [3], [2], [3, 2], [1], [3, 1], [2, 1], [3, 2, 1]]
B. [[3, 2, 1], [2, 1], [3, 1], [1], [3, 2], [2], [3], []]
C. [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
D. [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
E. None of the above.
查看答案与解析
解析:
这个函数生成列表的所有子集。
对于 [1, 2, 3],子集是:
[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]
答案:C. [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
Question 14
What is the value of xs after the following is evaluated?
xs = "abc"
ys = xs
ys[1] = "B"
A. "" (empty string)
B. "abc"
C. "aBc"
D. Error
E. None of the above.
查看答案与解析
解析:
字符串是不可变的,不能通过索引修改。
答案:D. Error
Question 15
What is the value of zs after executing the following?
ys = [1, 2]
zs = [4]
ys.extend([3])
zs.append(ys)
A. [4, [1, 2, 3]]
B. [4, 1, 2, 3]
C. [4, 3, 1, 2]
D. Error
E. None of the above.
查看答案与解析
解析:
ys.extend([3]) 将 3 添加到 ys 中,ys 变为 [1, 2, 3]。
zs.append(ys) 将整个 ys 作为一个元素添加到 zs 中,所以 zs 变为 [4, [1, 2, 3]]。
答案:A. [4, [1, 2, 3]]
Question 16
Consider the function foo defined below that computes the area of a circle with integer radius. What is the type of its return value?
def foo(radius: int):
"""
Precondition: radius > 0
"""
area = 3.14159 * radius ** 2
A. int
B. float
C. str
D. char
E. None of the above.
查看答案与解析
解析:
3.14159 是浮点数,与整数运算后结果是浮点数。
答案:B. float
Question 17
Suppose we want to assign True to the name validate when a user has typed only the single letter 'a', 'b', 'c', or 'd'. Which proposition should replace #sub to accomplish this?
value = input("Enter a single character: ")
validate = #sub
A. value == "a" or "b" or "c" or "d"
B. value in "abcd"
C. value not in "efghijklmnopqrstuvwxyz"
D. value in ["a", "b", "c", "d"]
E. More than one of the above.
查看答案与解析
解析:
A 错误:value == "a" or "b" 这种写法总是 True。
B 正确:value in "abcd" 可以检查字符串是否是 'a'、'b'、'c'、'd' 之一。
C 错误:会接受其他字符。
D 正确:value in ["a", "b", "c", "d"] 也能正确判断。
所以 B 和 D 都正确。
答案:E. More than one of the above.
Question 18
Which statement below is false?
A. Object oriented programming is no more powerful than imperative programming.
B. A constant value in Python can be modified.
C. We do not have to verify preconditions because it is the user's fault for breaking them.
D. Only immutable types can be keys in dictionaries.
E. All statements are true.
查看答案与解析
解析:
C 是错误的。即使是用户破坏了前置条件,程序员也应当在代码中进行适当的校验。
答案:C. We do not have to verify preconditions because it is the user's fault for breaking them.
Question 19
What tuple is assigned to ans when the following code is executed?
def foo(xs: tuple) -> tuple:
a, b = xs
a, b = b, a % b
return (a, b)
ans = foo(foo((3,5)))
A. (2, 2)
B. (2, 3)
C. (3, 2)
D. (3, 3)
E. None of the above.
查看答案与解析
解析:
第一次调用 foo((3,5)):
- a, b = 3, 5
- a, b = 5, 3 % 5 = 5, 3
- 返回 (5, 3)
第二次调用 foo((5,3)):
- a, b = 5, 3
- a, b = 3, 5 % 3 = 3, 2
- 返回 (3, 2)
答案:C. (3, 2)
Question 20
What can replace #sub so that "Drake is overrated" is assigned to ys?
xs = ["Drake", " ", "is", " ", "overrated"]
ys = #sub
A. join(xs)
B. xs.join('')
C. ''.join(xs)
D. More than one of the above.
E. None of the above.
查看答案与解析
解析:
''.join(xs) 将列表中的字符串用空字符串连接起来。
答案:C. ''.join(xs)
Question 21
What is the most appropriate type hint (i.e. type contract) for the following?
def foo(x, y):
for z in y:
if (" "+z) in x:
x[" "+z] += 1
return sum(x[k] for k in x)
A. def foo(x: dict[int, int], y: list[int]) -> int:
B. def foo(x: dict[int, str], y: list[int]) -> int:
C. def foo(x: dict[str, int], y: list[str]) -> int:
D. def foo(x: dict[str, int], y: str) -> int:
E. None of the above.
查看答案与解析
解析:
" "+z 是字符串,所以 x 的键是字符串。
x[" "+z] += 1 说明 x 的值是整数。
for z in y 说明 y 是可迭代的,且 z 是字符串。
答案:C. def foo(x: dict[str, int], y: list[str]) -> int:
Question 22
What type of error does the following code throw?
x =
if x > 0:
y[x] = 1
else:
y[0] = 1
A. KeyError
B. IndexError
C. SyntaxError
D. NameError
E. This is valid Python code.
查看答案与解析
解析:
x = 是语法错误,缺少赋值表达式。
答案:C. SyntaxError
Question 23
What is the value of a after the following code has been executed.
xss = [[1], [2,3], [1,2,3], [4,5,6]]
ys = [2, 3]
a = [ys[0] in xs and ys[1] in xs for xs in xss]
A. [True]
B. [False]
C. [False, True, True, False]
D. [True, False, False, True]
E. None of the above.
查看答案与解析
解析:
检查每个子列表是否同时包含 2 和 3:
[[1]] → False
[[2,3]] → True
[[1,2,3]] → True
[[4,5,6]] → False
答案:C. [False, True, True, False]
Question 24
What is stored in ans after the following is executed, supposing the user enters "25" and then "30".
x = input("Enter a number: ")
y = input("Enter a number: ")
ans = int(x + y)
A. 55
B. "55"
C. 2530
D. "2530"
E. Error
查看答案与解析
解析:
input() 返回字符串,x + y 是字符串拼接 "2530",然后 int("2530") 转换为整数 2530。
答案:C. 2530
Question 25
What is assigned to ans after executing the following code?
def foo(x, y):
if not x % 2:
return foo(x//2, y-1)
if not y:
return x+y
return foo(x-1, y-1)
ans = foo(3, 4)
A. 1
B. 2
C. 4
D. 7
E. RecursionError
查看答案与解析
解析:
foo(3,4) → foo(2,3) → foo(1,2) → foo(0,1) → foo(0,0) → 0+0=0
答案:E. RecursionError
Question 26
What is the value of xs after executing the following?
xs = [[1], [2, 3], [4, 5, 6]]
for x in xs:
x.extend(x)
A. [[1], [2, 3], [4, 5, 6]]
B. [[1], [1], [2, 3], [2, 3], [4, 5, 6], [4, 5, 6]]
C. [1, 1], [2, 3, 2, 3], [4, 5, 6, 4, 5, 6]]
D. Error
E. None of the above.
查看答案与解析
解析:
x.extend(x) 将每个子列表与其自身拼接。
[1] → [1, 1]
[2, 3] → [2, 3, 2, 3]
[4, 5, 6] → [4, 5, 6, 4, 5, 6]
答案:C. [1, 1], [2, 3, 2, 3], [4, 5, 6, 4, 5, 6]]
Question 27
Which statement is false?
A. Every if-then-else statement can be written using only if statements.
B. Every while loop can be written as a for loop.
C. Functions can be defined inside of functions.
D. Every for loop can be written as a while loop.
E. More than one of the above.
查看答案与解析
解析:
B 是错误的。while 循环可以无限循环,而 for 循环必须有明确的迭代对象。
答案:B. Every while loop can be written as a for loop.
Question 28
Which option does not assign the reverse of xs into a? Note: the reverse of [1, 2, 3] is [3, 2, 1].
A. a = xs[::-1]
B. a = xs.reverse()
C. a = xs[len(xs)::-1]
D. a = xs[-1::-1]
E. None of the above.
查看答案与解析
解析:
xs.reverse() 原地修改列表,返回 None。
答案:B. a = xs.reverse()
Question 29
Consider the following function.
def foo(xss: list[list[int]]) -> bool:
for k, xs in enumerate(xss):
for x in xs:
for ys in xss[:k]:
if x in ys:
return False
for ys in xss[k+1:]:
if x in ys:
return False
return True and len(xss) > 1
What best describes foo's behaviour? Note: A list is said to be made up of elements.
A. foo returns False only when there are two distinct elements of xss that are equal.
B. foo returns False only when there are two distinct elements of xss that have a common element.
C. foo returns True only when there is an empty list in xss.
D. foo always returns False.
E. foo always returns True.
查看答案与解析
解析:
函数检查每个子列表中的元素是否在其他子列表中出现过。
如果有任何元素在多个子列表中出现,返回 False。
答案:B. foo returns False only when there are two distinct elements of xss that have a common element.
Question 30
What is the purpose of "getter" 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. None of the above.
查看答案与解析
解析:
Getter(获取器)是专门用于读取对象私有属性的方法。
答案:B. They are used to retrieve the value of a private variable.
Question 31
How many of the following expressions evaluate to False?
bool("") # the empty string
bool(" ") # space
bool(-1)
bool(0)
bool([])
A. 1
B. 2
C. 3
D. 4
E. 5
查看答案与解析
解析:
空字符串、0、空列表在布尔上下文中为 False。
空格字符串、非零数字为 True。
答案:C. 3
Question 32
Consider the following assignments.
xss = [[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30]]
yss = [[10, 11, 12],
[16, 17, 18],
[22, 23, 24]]
How many of the following expressions are equivalent to yss?
[xs[-3:] for xs in xss[1:4]]
[xs[3:] for xs in xss[1:-1]]
[xs[-3:] for xs in xss[1:4]]
[xs[3:] for xs in xss[-4:4]]
A. 0
B. 1
C. 2
D. 3
E. 4
查看答案与解析
解析:
xss[1:4] 是第 2 到第 4 行,xs[-3:] 是每行的最后 3 个元素。
所以 [xs[-3:] for xs in xss[1:4]] 和 [xs[3:] for xs in xss[1:-1]] 都等于 yss。
答案:C. 2
Question 33
What is printed after executing the following?
x, stars = 1, ''
while x <= 4:
print(stars)
stars = '*' * x
x *= 2
A. *
B. *
**
C. *
**
D. *
**
E. Infinitely many stars.
查看答案与解析
解析:
x 从 1 开始,每次乘以 2,直到超过 4。
所以打印:
- x=1: ''
- x=2: '*'
- x=4: '**'
**答案:B. *
**
**
Question 34
What exception should be used at <Error> to complete the function?
def validate() -> int:
"""
Prompts the user to enter an integer.
Repeats until a number is entered.
"""
try:
return int(input("Enter an integer "))
except <Error>:
return validate()
A. ValueError
B. TypeError
C. NameError
D. InputError
E. None of the above.
查看答案与解析
解析:
如果输入不能被 int() 转换,比如输入字母,会抛出 ValueError。
答案:A. ValueError
Question 35
Which type cannot be used as a key in a dictionary?
A. int
B. str
C. list
D. tuple
E. None of the above.
查看答案与解析
解析:
字典的键必须是可哈希的(hashable)。列表是不可哈希的,不能作为字典的键。
答案:C. list
Question 36
The following code generates the window to its right. What replaces #sub to generate it?
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.LEFT, tk.RIGHT, tk.TOP)
B. (tk.BOTTOM, tk.RIGHT, tk.TOP, tk.BOTTOM)
C. (tk.BOTTOM, tk.RIGHT, tk.LEFT, tk.BOTTOM)
D. (tk.BOTTOM, tk.LEFT, tk.LEFT, tk.LEFT)
E. None of the above.
查看答案与解析
解析:
tk.BOTTOM 会让标签从下到上排列。
答案:A. (tk.BOTTOM, tk.LEFT, tk.RIGHT, tk.TOP)
The following four questions refer to the following class definition.
class A():
def __init__(self, x: int) -> None:
self._x = x
self.y = 0
def f(self, x: int) -> int:
return 2*x
def g(self, x: int) -> int:
return self.f(self.y)
class B(A):
def __init__(self, x: int, y: int) -> None:
super().__init__(x)
self.y = y
def f(self, x: int) -> int:
return A.f(self, self.y) + x
class C(B):
def __init__(self, x: int) -> None:
super().__init__(x, 5)
def h(self) -> int:
return self.g(self.y) + super().f(self._x)
class D(C):
def __init__(self, x: int, y: int, z: int) -> None:
super().__init__(x)
self._y += 5
self._z = z
def g(self, x: int, y: int, z: int) -> int:
return x*y*z + self._x + self._y + self._z
a = A(1)
b = B(1, 2)
c = C(3)
d = D(4, 5, 6)
Question 37
What does a.g(5) return?
A. 2
B. 6
C. 10
D. Error
E. None of the above.
查看答案与解析
解析:
a = A(1),所以 self._x = 1,self.y = 0
a.g(5) 调用 self.f(self.y),即 self.f(0)
self.f(0) 返回 2*0 = 0
答案:A. 2
Question 38
What does b.f(4) return?
A. 6
B. 8
C. 10
D. Error
E. None of the above.
查看答案与解析
解析:
b = B(1, 2),所以 self._x = 1,self.y = 2
b.f(4) 调用 A.f(self, self.y) + x,即 A.f(self, 2) + 4
A.f(self, 2) 返回 2*2 = 4
所以 4 + 4 = 8
答案:B. 8
Question 39
What does c.h() return?
A. 6
B. 15
C. 28
D. Error
E. None of the above.
查看答案与解析
解析:
c = C(3),所以 self._x = 3,self.y = 5
c.h() 调用 self.g(self.y) + super().f(self._x)
self.g(self.y) 调用 self.f(self.y),即 self.f(5)
self.f(5) 调用 A.f(self, self.y) + x,即 A.f(self, 5) + 5
A.f(self, 5) 返回 2*5 = 10
所以 self.f(5) = 10 + 5 = 15
super().f(self._x) 调用 A.f(self, 3),返回 2*3 = 6
所以 15 + 6 = 21
答案:E. None of the above.
Question 40
What does d.g(1, 2, 3) return?
A. 28
B. 32
C. 36
D. Error
E. None of the above.
查看答案与解析
解析:
d = D(4, 5, 6),所以 self._x = 4,self._y = 10,self._z = 6
d.g(1, 2, 3) 调用 x*y*z + self._x + self._y + self._z
即 1*2*3 + 4 + 10 + 6 = 6 + 4 + 10 + 6 = 26
答案:E. None of the above.