跳到主要内容

Semester 1, 2024 Midterm Exam

Question 1
What is the appropriate type-hint for the following function?

def foo(data, key):
acc = 0
for k in data[key]:
acc += k
return acc // len(data[key])

A. foo(data: dict[int, list[int]], key: str) -> float
B. foo(data: dict[str, list[int]], key: str) -> int
C. foo(data: dict[int, list[str]], key: str) -> float
D. foo(data: dict[str, list[str]], key: str) -> int
E. More than one of the above

查看答案与解析

解析:

  • data[key] 返回列表
  • k 是数字(因为 acc += k
  • acc // len(data[key]) 返回整数
  • 所以 data 是字典,key 是字符串,value 是整数列表
  • 返回类型是整数

答案:B. foo(data: dict[str, list[int]], key: str) -> int


Question 2
What is the value of y after only the following has been executed?

y = 0
for x in "ABCDE":
if x == 'B' or 'C' or 'D' or 'E':
y += 1

A. 0
B. 4
C. 5
D. Error
E. None of the above

查看答案与解析

解析:

  • if x == 'B' or 'C' or 'D' or 'E' 等价于 if (x == 'B') or ('C') or ('D') or ('E')
  • 非空字符串 'C', 'D', 'E' 都是 True
  • 所以条件总是为 True
  • 循环执行 5 次,每次 y += 1
  • 最终 y = 5

答案:C. 5


Question 3
What is the value of xs after only the following code has been executed?

ys = [0, 1]
xs = [ys, ys]
ys.extend([2])

A. [[0, 1], [0, 1]]
B. [[0, 1, 2], [0, 1]]
C. [[0, 1, 2], [0, 1, 2]]
D. Error
E. None of the above

查看答案与解析

解析:

  • xs = [ys, ys] 创建了两个对同一列表的引用
  • ys.extend([2]) 修改了原始列表
  • 所以 xs 中的两个元素都指向修改后的列表
  • 最终 xs = [[0, 1, 2], [0, 1, 2]]

答案:C. [[0, 1, 2], [0, 1, 2]]


Question 4
What is the best description of the behaviour of the following function?

def bar(xs: list) -> bool:
i = -1
for x in xs:
i += 1
return xs and xs[i] != x

A. bar checks if all members of xs are the same.
B. bar checks if all members of xs are different.
C. bar always returns True.
D. bar always returns False.
E. bar always throws errors.

查看答案与解析

解析:

  • 函数在第一次循环就返回
  • xs and xs[i] != x 中:
    • xs 非空时为 True
    • xs[i] 就是 x
    • 所以 xs[i] != x 总是 False
  • 最终返回 False

答案:D. bar always returns False.


Question 5
What is the value of x after only the following code is run?

x = 1

def foo(y) -> int:
global x
x = x + y
return

foo(x)
foo(x)

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

查看答案与解析

解析:

  • 第一次 foo(x)x = 1 + 1 = 2
  • 第二次 foo(x)x = 2 + 2 = 4
  • 最终 x = 4

答案:C. 4


Question 6
What is the value of xs after the following is evaluated?

xs = "toque"
ys = xs[::]
ys[0] = "T"

A. "" (empty string)
B. "toque"
C. "Toque"
D. Error
E. None of the above

查看答案与解析

解析:

  • 字符串在 Python 中是不可变的
  • ys[0] = "T" 试图修改字符串
  • 会触发 TypeError

答案:D. Error


Question 7
Which of the following expressions can generate an error when x = dict()?

A. x[(1,)] = 1
B. x["1"] = 1
C. x[1] == 1
D. 1 in x
E. More than one of the above

查看答案与解析

解析:

  • A. x[(1,)] = 1 ✅ 合法,元组是可哈希的
  • B. x["1"] = 1 ✅ 合法,字符串是可哈希的
  • C. x[1] == 1 ✅ 合法,只是比较,不会报错
  • D. 1 in x ✅ 合法,检查键是否存在

答案:E. More than one of the above


Question 8
What is the value of x after running the following code?

s = 'drake is mid'
x = s[:-3:-1]

A. 'di'
B. 'id'
C. 'dim'
D. 'mid'
E. '' (empty string)

查看答案与解析

解析:

  • s[:-3:-1] 是切片操作
  • -3 表示从倒数第3个字符开始
  • -1 表示步长为-1(反向)
  • 从后往前数第3个字符是 'm',然后反向取两个字符
  • 所以结果是 'id'

答案:B. 'id'


Question 9
How many of the following statements evaluate to True?

bool("False")
bool(True > False)
bool([1, 2, 3] and 1/0)

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

查看答案与解析

解析:

  • bool("False")True(非空字符串)
  • bool(True > False)True(True > False 为 True)
  • bool([1, 2, 3] and 1/0)Error(除零错误)

答案:E. Error


Question 10
Consider the function foo defined below that computes the salary of a minimum wage employee that has worked hours number of hours. What type of value does foo return?

def foo(hours: int):
"""
Precondition: hours > 0
"""
salary = 23.23 * hours

A. int
B. float
C. str
D. char
E. None of the above

查看答案与解析

解析:

  • 23.23 是浮点数
  • hours 是整数
  • 浮点数乘以整数结果是浮点数
  • 函数没有返回值,返回 None

答案:E. None of the above


Question 11
What does the following arithmetic expression evaluate to?

(1 + 1) ** 3 % 8 - 2 ** (^1) ** 2 - 20 // 4
查看答案与解析

解析:

  • ^1 是无效的语法
  • 会触发 SyntaxError

答案:Error


Question 12
Re-write the following code snippet so that it uses while loops instead of for loops.

ans = 0
for y in z:
for x in y:
ans += len(x)
查看答案与解析

解析:

ans = 0
i = 0
while i < len(z):
j = 0
while j < len(z[i]):
ans += len(z[i][j])
j += 1
i += 1

Question 13
Suppose we have run the following code and the user has typed something.

value = input("Enter a single digit: ")

Write a Python expression that evaluates to True only when the user has typed a single digit.

查看答案与解析

解析:

value.isdigit() and len(value) == 1

Question 14
Implement the following function according to the specification.

def foo(xs: str) -> str:
"""
Return the input string converted to title-case.

This is, return a version of the input spring where words start with
uppercased characters and all remaining cased characters have lower case.

>>> foo("run spot run")
'Run Spot Run'
>>> foo("rUn SpOt rUn")
'Run Spot Run'
>>> foo("a b 1 %")
'A B 1 %'
"""
查看答案与解析

解析:

def foo(xs: str) -> str:
words = xs.split()
result = []
for word in words:
if word:
result.append(word[0].upper() + word[1:].lower())
else:
result.append(word)
return ' '.join(result)

Question 15
Implement the following function according to the specification.

def foo(xs: str) -> str:
"""
Return the character of that occurs most frequently.

If there is a tie for the most frequent element the element with least
index is returned.

Precondition:
len(xs) > 0

>>> foo("AAABB")
'A'
>>> foo("AABBB")
'B'
>>> foo("ABABAB")
'A'
>>> foo("BABABA")
'B'
"""
查看答案与解析

解析:

def foo(xs: str) -> str:
counts = {}
for char in xs:
counts[char] = counts.get(char, 0) + 1

max_count = max(counts.values())
for char in xs:
if counts[char] == max_count:
return char