14 — Practice solutions

← Questions

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 count

Expected results: 2, 0, 0. Count matching items, including duplicate occurrences.

14B

def sum_before_stop(readings):
    total = 0
    for reading in readings:
        if reading == -1:  # Stop before adding the sentinel.
            break
        total += reading
    return total

Expected results: 1 and 0. Without a sentinel, all readings are summed. Checking for the sentinel after adding would wrongly include −1.

14C

valuetotal beforetotal < 4?total after
20True2
52True7
17False6
46False5

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.