关于python:为什么这种暴力算法会产生错误的结果?

Why is this brute force algorithm producing the incorrect result?

我正在尝试编写一个蛮力算法,根据docstring中的条件,将一群奶牛的旅行次数最小化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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行。我反复检查了代码,它返回一个次优答案:

1
2
3
4
5
6
7
[['Florence', 'Lola'],
 ['Maggie', 'Milkshake', 'Moo Moo'],
 ['Herman'],
 ['Oreo'],
 ['Millie'],
 ['Henrietta'],
 ['Betsy']]

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


这里的问题是:

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

要执行此操作,请将最后一行更改为:

1
min(valid_trips, key=len)