alexqwx
alexqwx

Reputation: 147

Why is this brute force algorithm producing the incorrect result?

I'm trying to write a brute-force algorithm that minimises the number of journeys of a herd of cows, subject to the conditions in the docstring.

def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    def weight(sub):
        sum = 0
        for e in sub:
            sum += cows[e]
        return sum

    valid_trips = []
    for part in list(get_partitions(cows)):
        if all(weight(sub) <= limit for sub in part):
            valid_trips.append(part)
    return min(valid_trips)

(The function get_partitions and the dictionary cows have been given in the question)

Where have I gone wrong? I've checked the weight function (that evaluates the weight of a given spaceship trip), so it must be in the last 5 lines. I've checked the code over and over, and it returns a sub-optimal answer:

[['Florence', 'Lola'],
 ['Maggie', 'Milkshake', 'Moo Moo'],
 ['Herman'],
 ['Oreo'],
 ['Millie'],
 ['Henrietta'],
 ['Betsy']]

The syntax is fine; there are no errors being produced, yet I have a sub-optimal (but valid) answer. Why is this?

Upvotes: 0

Views: 294

Answers (1)

Jared Goguen
Jared Goguen

Reputation: 9010

The question here is:

How do I find the shortest sublist in a nested list?

To do this, change the last line to:

min(valid_trips, key=len)

Upvotes: 2

Related Questions