Chapter 10: Algorithms (Solutions to Even-Numbered Exercises)

Question 2

a)

index = 0
value = sequence[0]
for i in range(1, len(sequence)):
    if sequence[i] < value:
        index = i
        value = sequence[i]

b)

def min_index(sequence):

    index = 0
    value = sequence[0]

    for i in range(1, len(sequence)):
        if sequence[i] < value:
            index = i
            value = sequence[i]

    return (index, value)

c)

def min_or_max_index(sequence, find_min):

    index = 0
    value = sequence[0]

    for i in range(1, len(sequence)):
        if find_min:
            if sequence[i] < value:
                index = i
                value = sequence[i]
        else:
            if sequence[i] > value:
                index = i
                value = sequence[i]

    return (index, value)

The test inside the loop can be simplified to:

        if find_min and (sequence[i] < value):
            index = i
            value = sequence[i]
        elif (not find_min) and (sequence[i] > value):
            index = i
            value = sequence[i]

    return (index, value)

Many other simplifications introduce bugs.

Question 4

If the functions to find the two smallest values in a list are passed a list of length 1, they will fail with an IndexError on the very first line (which compares L[0] with L[1]). They could return the same index twice, but that would force users to do extra work, since they will almost always assume that the two indices being returned are distinct. Instead, the functions should raise a ValueError exception and report that the input list is invalid (too short). The same should happen if they are passed a list of length 0.