17 — Practice solutions
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 resultResult [5, 7, 9]. Reset total before summing each column, inside the outer loop and before the inner loop.
Reasoning
One output value per column means the outer loop visits columns. The inner loop adds that column’s entries across rows. Reset total once per column; resetting it for each row would retain only the last contribution.
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 resultResult [“b”, “a”]. Repeated items are counted but emitted only once. Traversing original items makes the specified first-appearance order explicit.
Reasoning
Distinguish counting occurrences from emitting distinct answers. First count all occurrences, then find the largest count, then traverse the original input to emit each tied item once. Sorting would risk violating first-appearance order.