12 — Practice solutions
These are independently written explanations, not an official marking scheme.
12A
Input: list and target. Output: list of matching indices. Visit each valid index, compare its value with target, append the index when equal. Expected results: [0, 2] and [].
def positions(values, target):
result = []
for index in range(len(values)):
if values[index] == target:
result.append(index) # The question asks for position, not value.
return resultReasoning
The output contains indices. Iterating values alone would not directly give the positions requested, so use an index traversal. Every matching index is appended; returning immediately would lose later matches. Empty input supplies no indices, so an empty result follows naturally.
12B
def smallest_values(values):
if len(values) == 0:
return []
minimum = values[0] # A real candidate; works for positive and negative data.
for value in values:
if value < minimum:
minimum = value
result = []
for value in values:
if value == minimum:
result.append(value) # Preserve duplicate occurrences and input order.
return resultStarting at 0 makes the alleged minimum stay 0 for [5, 7], even though 0 is absent, so no actual values would be returned. Using the first item provides a real candidate.
Reasoning
Unlike a string length, the smallest number is not safely initialised to0. First handle the empty list so index 0 is safe, then start with an actual candidate. The second pass collects every occurrence rather than a set of distinct values.