Semester 1, 2023 Exam
Question 1
Which of the following cannot be a key in a dictionary?
A. '123'
B. (1, 2, 3)
C. 123
D. [1, 2, 3]
E. None of the above
查看答案与解析
解析:
字典的键必须是可哈希的(hashable)。列表是不可哈希的,不能作为字典的键。
答案:D. [1, 2, 3]
Question 2
Suppose the following functions have been defined.
def foo(n):
return n + n
def bar(n):
print(n + n)
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)
E. None of the above
查看答案与解析
解析:
bar() 函数返回 None,不能与数字相乘。
答案:D. z = 2 * bar(3)
Question 3
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.
E. None of the above
查看答案与解析
解析:
类型提示(type hints)只是提示,Python 不会强制检查类型。
答案:A. Type-hints signal the user of the expected input to a function.
Question 4
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. None of the above
查看答案与解析
解析:
Python 中私有变量通常以下划线 _ 开头。
答案:C. _maximum_volume
Question 5
Suppose the following function definition has been made.
def foo(x):
if x == 1:
return x
return foo(x-1) * x
What will foo(0) return?
A. -
B. 0
C. 1
D. Error
E. None of the above
查看答案与解析
解析:
foo(0) 会无限递归,因为 x 会一直减小,永远不会等于 1。
答案:D. Error
Question 6
Suppose the following has been executed by Python.
xs = [1, 2, 3, 4, 5, 6]
ys = xs[-3:-1]
What is stored in ys?
A. [4, 5]
B. [4, 5, 6]
C. [5, 4]
D. []
E. None of the above
查看答案与解析
解析:
xs[-3:-1] 从倒数第 3 个元素到倒数第 1 个元素(不包括),即 [4, 5]。
答案:A. [4, 5]
Question 7
Which option will throw an IndexError in the following code when replacing #sub?
xs = [0, 1, 2, 3]
#sub
A. xs[-len(xs)]
B. xs[1-len(xs)]
C. xs[-1-len(xs)]
D. xs[len(xs)-1]
E. None of the above
查看答案与解析
解析:
xs[-1-len(xs)] 会超出索引范围,因为 len(xs) = 4,所以 -1-4 = -5,超出了列表的索引范围。
答案:C. xs[-1-len(xs)]
Question 8
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.
E. None of the above
查看答案与解析
解析:
bind() 方法用于为控件添加事件处理器。
答案:B. To add an event handler to a widget.
Question 9
What is stored in count after the following is evaluated?
count = 0
for x in "abcdef":
if x == "a" or "c" or "e" or "g":
count += 1
A. 0
B. 3
C. 4
D. 6
E. None of the above
查看答案与解析
解析:
if x == "a" or "c" or "e" or "g" 实际理解为 (x == "a") or ("c") or ("e") or ("g"),由于非空字符串在布尔上下文中为 True,所以条件永远为 True。
答案:D. 6
Question 10
What does the following expression evaluate to?
['98'] + ['76']
A. '9876'
B. ['9876']
C. ['98', '76']
D. Error
E. None of the above
查看答案与解析
解析:
列表加法是拼接,所以 ['98'] + ['76'] = ['98', '76']。
答案:C. ['98', '76']
Question 11
Consider the following function.
def foo(count: int) -> bool:
while count < 0:
count += 1
return count < 0
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.
E. None of the above
查看答案与解析
解析:
如果 count 是负数,while 循环会一直执行,直到 count 变为 0,然后 return count < 0 返回 False。
如果 count 是非负数,while 循环不会执行,直接 return count < 0,也是 False。
答案:C. Always False.
Question 12
What does the following expression evaluate to?
7-4+
A. 0
B. 6
C. 7
D. Error
E. None of the above
查看答案与解析
解析:
7-4+ 是语法错误,因为 + 后面没有操作数。
答案:D. Error
Question 13
Consider the following incomplete code.
import tkinter as tk
window = tk.Tk()
this_side = ?
alice = tk.Label(text="Alice")
alice.pack(side=this_side)
bob = tk.Label(text="Bob")
bob.pack(side=this_side)
carol = tk.Label(text="Carol")
carol.pack(side=this_side)
window.mainloop()
What do we assign this_side in order to produce the following window?
A. tk.LEFT
B. tk.RIGHT
C. tk.TOP
D. tk.BOTTOM
E. None of the above
查看答案与解析
解析:
tk.LEFT 会让标签从左到右排列。
答案:A. tk.LEFT
Question 14
What is the value of zs after the following is evaluated?
ys = ['a', 'b']
zs = ['t']
ys.extend(['c'])
zs.append(ys)
A. ['t', ['a', 'b', 'c']]
B. ['t', 'a', 'b', 'c']
C. ['t', ['c', 'a', 'b']]
D. ['t', 'c', 'a', 'b']
E. None of the above
查看答案与解析
解析:
ys.extend(['c']) 将 'c' 添加到 ys 中,ys 变为 ['a', 'b', 'c']。
zs.append(ys) 将整个 ys 作为一个元素添加到 zs 中,所以 zs 变为 ['t', ['a', 'b', 'c']]。
答案:A. ['t', ['a', 'b', 'c']]
Question 15
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.
E. None of the above
查看答案与解析
解析:
if-then-else 可以用多个 if-then 语句实现。
答案:C. Every if-then-else statement can be written using only if-then statements.
Question 16
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 [])
E. None of the above
查看答案与解析
解析:
空列表在布尔上下文中为 False,所以 not xs 为 True。
答案:A. bool(not xs)
Question 17
What error, if any, does Python raise when the following is executed?
def foo(x: str) -> str:
return 3*x
foo(2.3)
A. TypeError
B. ValueError
C. NameError
D. No error is generated.
E. None of the above
查看答案与解析
解析:
foo(2.3) 传入的是 float,而函数预期是 str,会抛出 TypeError。
答案:A. TypeError
Question 18
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.
E. None of the above
查看答案与解析
解析:
Setter(设置器)是专门用于修改对象私有属性的方法。
答案:A. They are used to change the values of private variables.
Question 19
What is the value of ys after the following is executed?
xs = "hello world"
ys = xs
xs[0] = "H"
xs[6] = "W"
A. "hello world"
B. "Hello World"
C. "xs"
D. Error
E. None of the above
查看答案与解析
解析:
字符串是不可变的,不能通过索引修改。
答案:D. Error
Question 20
How many of the following expressions evaluate to True?
bool("") # empty string
bool(" ") # one space
bool([0])
bool(-1)
A. 1
B. 2
C. 3
D. 4
E. None of the above
查看答案与解析
解析:
空字符串为 False,空格字符串为 True,非空列表为 True,非零数字为 True。
答案:C. 3
Question 21
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?
def concat(xss: list[str]) -> str:
"""
>>> concat(["a", "b", "c"])
'abc'
"""
n, base = #sub
if len(xs) == n:
return base
return xss[0] + concat(xss[1:])
A. (0, xs[0])
B. (1, xs[0])
C. (0, "")
D. (1, "")
E. None of the above
查看答案与解析
解析:
当列表为空时,应返回空字符串。
答案:C. (0, "")
Question 22
What is the most appropriate type hint (i.e. type contract) for the following?
def foo(x, y):
ans = ""
for n in x:
for m in y:
ans += n*m
return ans
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]:
E. None of the above
查看答案与解析
解析:
x 和 y 都是可迭代的,ans 是字符串。
答案:B. foo(x: int, y: list[str]) -> str:
Question 23
What error is raised after executing the following?
for k in range(10):
count = count + 1
print(count)
A. TypeError
B. ValueError
C. NameError
D. No error is generated.
E. None of the above
查看答案与解析
解析:
count 未定义,会抛出 NameError。
答案:C. NameError
Question 24
Which function requires the use of 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.
E. None of the above
查看答案与解析
解析:
统计函数调用次数需要使用全局变量。
答案:B. A function that returns the number of times the function has been called.
Question 25
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.
E. None of the above
查看答案与解析
解析:
Python 列表可以包含不同类型的元素。
答案:D. All are valid lists.
Question 26
What is stored in xs after the following is executed?
xs = [1, 2, 3].reverse()
given that
>>> help(list.reverse)
reverse(self, /)
Reverse IN PLACE.
(END)
A. [1, 2, 3]
B. [3, 2, 1]
C. None
D. Error
E. None of the above
查看答案与解析
解析:
reverse() 方法原地修改列表,返回 None。
答案:C. None
Question 27
What error is generated by executing the following?
x = int("three")
A. TypeError
B. ValueError
C. NameError
D. No error is generated.
E. None of the above
查看答案与解析
解析:
"three" 不能被转换为整数,会抛出 ValueError。
答案:B. ValueError
Question 28
Suppose the following function definition has been made.
def foo(x: int, y: int):
print(x/y)
What is type(foo(1, 2))?
A. <class 'int'>
B. <class 'float'>
C. <class 'str'>
D. <class 'NoneType'>
E. None of the above
查看答案与解析
解析:
foo() 函数没有返回值,默认返回 None。
答案:D. <class 'NoneType'>
Question 29
Suppose the following lines of code have been executed.
class Artist():
def __init__(self, name: str, num_good_songs: int) -> None:
self._name = name
self._num_good_songs = num_good_songs
drake = Artist("Drake", 0)
drizzy = Artist("Drake", 1)
What is stored in drake._num_good_songs?
A. 0
B. 1
C. 'Drake'
D. Error
E. None of the above
查看答案与解析
解析:
drake 和 drizzy 是两个不同的实例,drake._num_good_songs 是 0。
答案:A. 0
Question 30
Given the following code:
x = input(" Enter the first number: ")
y = input(" Enter the second number: ")
print(f"x + y = {x+y}")
and assuming the user inputs 4 then 0. What is output?
A. x+y=x+y
B. x+y=
C. x+y=4+
D. x + y = 40
E. None of the above
查看答案与解析
解析:
input() 返回字符串,x+y 是字符串拼接。
答案:D. x + y = 40
Question 31
The next five questions refer to the following class definitions.
class A():
def __init__(self, x):
self.x = x
def f(self, x):
return self.g(x) - 1
def g(self, x):
return 2*x
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
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
def g(self, y):
return self.y + y
def f(self, x):
return super().f(x) - x
a = A(3)
b = B(2)
c = C(2, 4)
d = D(1, 3)
What does a.g(2) return?
查看答案与解析
解析:
a = A(3),所以 self.x = 3
a.g(2) 调用 A 类的 g 方法,返回 2 * 2 = 4
答案:4
Question 32
What does a.f(2) return?
查看答案与解析
解析:
a.f(2) 调用 self.g(2) - 1
self.g(2) 返回 4(见上一题)
所以 4 - 1 = 3
答案:3
Question 33
What does a.g(3) return?
查看答案与解析
解析:
a.g(3) 调用 A 类的 g 方法,返回 2 * 3 = 6
答案:6
Question 34
What does a.f(3) return?
查看答案与解析
解析:
a.f(3) 调用 self.g(3) - 1
self.g(3) 返回 6(见上一题)
所以 6 - 1 = 5
答案:5
Question 35
What does d.f(2) return?
查看答案与解析
解析:
d = D(1, 3)
super().__init__(1) → self.x = 1
self.x += 3 → self.x = 4
self.y = 3
d.f(2) 调用 super().f(2) - 2
super().f(2) 调用 B 类的 f 方法,即 self.g(2) - 1
self.g(2) 调用 D 类的 g 方法,返回 self.y + 2 = 3 + 2 = 5
所以 super().f(2) = 5 - 1 = 4
最后 4 - 2 = 2
答案:2
Question 36
Write a function foo that satisfies the following specification.
def foo(f_path: str, word: str) -> list[str]:
"""
The text of a book with all punctuation removed is stored at <f_path>.
Each line of the file corresponds to one line of the book.
Return the list of words that appear immediately before an instance of
<word> in the file located at <f_path>.
Preconditions:
1. The file at <f_path> exists.
2. The first word of the file is NOT <word>
Example:
Suppose run.txt contains the following lines:
See spot run
run spot see
spot run spot
run see spot
see spot spot
>>> foo("run.txt", "spot")
['See', 'run', 'see', 'run', 'see', 'spot']
"""
查看答案与解析
解析:
需要读取文件,找出每个 "spot" 前面的单词。
处理步骤:
- 打开文件
- 遍历每一行
- 将每行按空格分割成单词列表
- 遍历单词列表,如果当前单词是 "spot",则前一个单词加入结果
- 返回结果列表
答案:
def foo(f_path: str, word: str) -> list[str]:
result = []
with open(f_path, 'r') as f:
for line in f:
words = line.strip().split()
for i in range(1, len(words)):
if words[i] == word:
result.append(words[i-1])
return result