14 — Practice solutions
These are independently written explanations, not an official marking scheme.
14A
def count_large(values, limit):
count = 0
for value in values:
if value > limit:
count += 1 # Count each matching occurrence once.
return countExpected results: 2, 0, 0. Count matching items, including duplicate occurrences.
Reasoning
“number of values” requires a counter, and “strictly greater” excludes the value equal to limit. Both7s count independently. The code returns one integer, not a tuple containing an unrequested sum.
14B
def sum_before_stop(readings):
total = 0
for reading in readings:
if reading == -1: # Stop before adding the sentinel.
break
total += reading
return totalExpected results: 1 and 0. Without a sentinel, all readings are summed. Checking for the sentinel after adding would wrongly include −1.
Reasoning
−1 terminates processing, but −2 is ordinary data. Test the sentinel before accumulation so it is excluded, and break so100 is never reached. Empty input or an immediate sentinel leaves the initial sum0.
14C
| value | total before | total < 4? | total after |
|---|---|---|---|
| 2 | 0 | True | 2 |
| 5 | 2 | True | 7 |
| 1 | 7 | False | 6 |
| 4 | 6 | False | 5 |
Final total is 5. The branch depends on the accumulated total before the update, so the same value may take a different branch in a different state.