Why is this brute force algorithm producing the incorrect result?

情到浓时终转凉″ 提交于 2019-12-12 05:38:29

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/44345237/why-is-this-brute-force-algorithm-producing-the-incorrect-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!