为什么这种强力算法会产生错误的结果?

时间:2017-06-03 14:57:32

标签: python brute-force

我试图编写一个蛮力算法,根据文档字符串中的条件,最大限度地减少一群奶牛的旅行次数。

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)

(函数get_partitions和字典cows已在问题中提供)

我哪里出错了?我检查了重量函数(评估给定飞船旅行的重量),所以它必须在最后5行。我一遍又一遍地检查了代码,它返回了一个次优答案:

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

语法很好;没有错误产生,但我有一个次优(但有效)的答案。这是为什么?

1 个答案:

答案 0 :(得分:1)

这里的问题是:

  

如何在嵌套列表中找到最短的子列表?

为此,请将最后一行更改为:

i