17 — Practice solutions

← Questions

These are independently written explanations, not an official marking scheme.

17A

def column_totals(grid):
    result = []
    for column in range(len(grid[0])):
        total = 0  # Fresh accumulator for this column, outside the row loop.
        for row in range(len(grid)):
            total += grid[row][column]
        result.append(total)
    return result

Result [5, 7, 9]. Reset total before summing each column, inside the outer loop and before the inner loop.

17B

def most_frequent(items):
    counts = {}
    for item in items:
        counts[item] = counts.get(item, 0) + 1
    maximum = 0
    for count in counts.values():
        if count > maximum:
            maximum = count
    result = []
    for item in items:
        if counts[item] == maximum and item not in result:  # Emit each tied key once.
            result.append(item)
    return result

Result [“b”, “a”]. Repeated items are counted but emitted only once. Traversing original items makes the specified first-appearance order explicit.