12 — Practice solutions

← Questions

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 result

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 result

Starting 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.