Semester 2, 2024 Midterm Exam
Question 1
What is the value of x after the following is evaluated?
cs = 'Doggy the dog'
x = cs[:-9:-3]
A. 'Dgt'
B. 'Dg'
C. 'gt'
D. 'g t'
E. None of the above
查看答案与解析
解析:
cs[:-9:-3]是切片操作-9表示从倒数第9个字符开始-3表示步长为-3(反向)- 从后往前数第9个字符是 'd',然后每隔3个字符取一个
- 所以结果是 'Dgt'
答案:A. 'Dgt'
Question 2
Which of the following is not a valid python statement when x = {0: 'empty', 1: 'one'}?
A. x[{2: 'two'}] = ''
B. x[[2]] = 'two'
C. x[2] = 'two'
D. x['2'] = 'two'
E. More than one of the above
查看答案与解析
解析:
- A.
x[{2: 'two'}]❌ 字典不能作为字典的key - B.
x[[2]]❌ 列表不能作为字典的key - C.
x[2]✅ 合法 - D.
x['2']✅ 合法
答案:E. More than one of the above
Question 3
Consider the function foo defined below that adds two strings. What type of value is stored in x?
def foo(word1: str, word2: str):
output = word1 + word
return output
return
x = foo(1, 2)
A. int
B. float
C. string
D. NoneType
E. Error
查看答案与解析
解析:
- 函数定义中有语法错误:
word未定义 - 调用时传入
int类型,与类型提示str不符 - 会触发
NameError
答案:E. Error
Question 4
What is the value of x after the following is evaluated?
x = 'Hello' + print('World')
A. 'Hello'
B. 'Hello World'
C. 'HelloWorld'
D. None
E. Error
查看答案与解析
解析:
print()返回None- 字符串不能与
None相加 - 会触发
TypeError
答案:E. Error
Question 5
What is the value of ys after the following is evaluated?
xs = ['0', '1', '2', '3']
ys = xs
ys[0][0] = '-'
A. ['-1', '1', '2', '3']
B. ['0', '1', '2', '3']
C. [-1, '1', '2', '3']
D. Error
E. None of the above
查看答案与解析
解析:
- 字符串在Python中是不可变的
ys[0][0]试图修改字符串的第一个字符- 会触发
TypeError
答案:D. Error
Question 6
What is the best description of the behaviour of the following function?
def bar(nums: list) -> bool:
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
A. bar only returns False when all numbers in nums are in increasing order.
B. bar only returns True when all numbers in nums are in increasing order.
C. bar always returns True.
D. bar always returns False.
E. bar always throws errors
查看答案与解析
解析:
- 函数检查列表是否按非递减顺序排列
- 如果发现任何元素小于前一个元素,返回 False
- 否则返回 True
- 所以只有当所有数字按非递减顺序排列时才返回 True
答案:B. bar only returns True when all numbers in nums are in increasing order.
Question 7
Which statement evaluates to True?
A. bool(False < 0)
B. bool('True' and 0)
C. bool('False' or [])
D. bool(0 * True)
E. More than one of the above
查看答案与解析
解析:
- A.
False < 0→False→bool(False)→False - B.
'True' and 0→0→bool(0)→False - C.
'False' or []→'False'→bool('False')→True - D.
0 * True→0→bool(0)→False
答案:C. bool('False' or [])
Question 8
What is the value of y after only the following code is run?
y = 0
for k, x in enumerate([1, 2, 0, 3]):
if k == 1 and 0:
y += 2*x
else:
y += x
A. 9
B. 7
C. 6
D. Error
E. None of the above
查看答案与解析
解析:
k == 1 and 0总是 False(因为 0 是假值)- 所以总是执行
else分支 - 累加所有 x 的值:1 + 2 + 0 + 3 = 6
答案:C. 6
Question 9
What is the appropriate type-hint for the following function?
def process_items(items, index):
count = 0
for item in items[index]:
count += len(item)
return count
A. process_items(items: dict[str, list[int]], index: int) -> int
B. process_items(items: dict[int, list[str]], index: int) -> float
C. process_items(items: dict[str, list[str]], index: str) -> int
D. process_items(items: dict[int, list[int]], index: str) -> int
E. None of the above
查看答案与解析
解析:
items[index]返回列表len(item)说明 item 是字符串- 所以 items 是字典,value 是字符串列表
- index 可以是任何可哈希类型
- 返回整数
答案:E. None of the above
Question 10
What is the value of the global variable a after the following code is executed?
def f(x):
a = x / 9
return a
a = 9
f(a)
A. 1
B. 9
C. 1.
D. Error
E. None of the above
查看答案与解析
解析:
- 函数内的
a是局部变量 - 不会影响全局变量
a - 所以全局变量
a保持为 9
答案:B. 9
Question 11
What does the following arithmetic expression evaluate to?
(7 > 3 + 4** (^1) **2) // 17 - 8 % 5 * False
查看答案与解析
解析:
^1是无效的语法- 会触发
SyntaxError
答案:Error
Question 12
Re-write the following code snippet to use a single if-elif-else expression instead of nested if-else statements.
if age >= 18:
if age < 65:
print("Adult")
else:
print("Senior")
else:
print("Minor")
查看答案与解析
解析:
if age >= 65:
print("Senior")
elif age >= 18:
print("Adult")
else:
print("Minor")
Question 13
Suppose we have run the following code and the user has typed something.
value = input("Enter a 3-digits number divisible by 4: ")
Write a Python expression that evaluates to True only when the user has typed a 3-digits number that is divisible by four.
查看答案与解析
解析:
value.isdigit() and len(value) == 3 and int(value) % 4 == 0
Question 14
Implement the following function according to its specification.
def transpose(matrix: list) -> list:
"""
Return the transpose of the input matrix.
This returns a new matrix where the rows and columns are swapped.
Precondition: len(matrix) > 0
>>> transpose([[1, 2, 3], [4, 5, 6]])
[[1, 4], [2, 5], [3, 6]]
>>> transpose([[1, 2], [3, 4], [5, 6]])
[[1, 3, 5], [2, 4, 6]]
>>> transpose([[1]])
[[1]]
"""
查看答案与解析
解析:
def transpose(matrix: list) -> list:
return [[matrix[j][i] for j in range(len(matrix))]
for i in range(len(matrix[0]))]
Question 15
Implement the following function according to its specification.
def first_unique_char(text: str) -> str:
"""
Return the first character of that does not repeat.
If all characters repeat, return an empty string.
Precondition:
len(text) > 0
>>> first_unique_char("swiss")
'w'
>>> first_unique_char("racecar")
'e'
>>> first_unique_char("aabbcc")
''
>>> first_unique_char("abcd")
'a'
>>> first_unique_char("a")
'a'
"""
查看答案与解析
解析:
def first_unique_char(text: str) -> str:
for i, char in enumerate(text):
if text.count(char) == 1:
return char
return ''