Python:查找数组总和

时间:2014-09-27 07:30:55

标签: python arrays integer sum

这项任务实际上对我来说很难。 我的任务是找出莎拉可以实现的最高幸福,因为她的行李容量和可供出售的物品。 Sarah带着一个最多可携带3件物品的袋子,总重量最多为w kg。 Sarah购买的所有物品必须同时放入她的包里。 例如: w = 97 items = [[17, 19], [22, 19], [65, 64], [21, 19], [27, 26], [19, 21], [58, 61], [43, 46], [1, 3], [44, 42], [22, 22], [52, 53], [10, 8], [37, 35], [60, 62], [42, 39], [36, 36], [62, 60], [50, 47], [62, 62], [47, 48], [15, 16], [12, 12], [6, 5], [30, 27], [52, 49], [30, 32], [3, 4], [21, 18], [58, 58], [43, 42], [50, 50], [41, 41], [60, 60], [55, 58], [64, 63], [32, 33], [11, 12], [11, 13], [46, 44], [22, 21], [20, 19], [47, 45], [24, 24], [35, 32], [28, 31], [14, 15], [35, 37], [9, 10], [23, 22], [45, 46], [34, 32], [34, 37], [37, 39], [42, 41], [59, 57], [24, 22], [15, 13], [33, 34], [3, 3], [55, 55]] 第一个数字是项目'重量。 第二个数字是项目'幸福价值。 任何人都知道如何计算这个?

2 个答案:

答案 0 :(得分:1)

这是0/1 knapsack problem。最优雅的解决方案是动态编程。您可以找到有关它的讲座here和解决方案here

我建议在查看解决方案之前先查看讲座并尝试自己编写代码。

答案 1 :(得分:-3)

我获得了105个幸福,项目[11, 13], [28, 31], [58, 61][28, 31], [34, 37], [35, 37]使用了所有可能的97个权重和所有3个保留位置。

# this allows for integers to be divided by integers and give a float result
# program is runnable in both python 2 and 3
from __future__ import division
from sys import exit
weight = 97
items = [[17, 19], [22, 19], [65, 64], [21, 19], [27, 26], [19, 21], [58, 61],
[43, 46], [1, 3], [44, 42], [22, 22], [52, 53], [10, 8], [37, 35], [60, 62],
[42, 39], [36, 36], [62, 60], [50, 47], [62, 62], [47, 48], [15, 16], [12, 12],
[6, 5], [30, 27], [52, 49], [30, 32], [3, 4], [21, 18], [58, 58], [43, 42],
[50, 50], [41, 41], [60, 60], [55, 58], [64, 63], [32, 33], [11, 12], [11, 13],
[46, 44], [22, 21], [20, 19], [47, 45], [24, 24], [35, 32], [28, 31], [14, 15],
[35, 37], [9, 10], [23, 22], [45, 46], [34, 32], [34, 37], [37, 39], [42, 41],
[59, 57], [24, 22], [15, 13], [33, 34], [3, 3], [55, 55]]

# this is about half of the problem: we must sort the items by the priority
# which which we want them.  this would be their happiness to weight ratio
sorted_items = sorted(items, key=lambda item: item[1] / item[0], reverse=True)

happiness = int()
for item1 in range(len(sorted_items) - 2):
    for item3 in range(item1 + 2, len(sorted_items)):
        for item2 in range(item1 + 1, item3):
            # try to use as much weight as possible, we don't want
            # our bag to go underfilled with 3 efficient but light items
            if (sorted_items[item1][0] +
                sorted_items[item2][0] +
                sorted_items[item3][0] <= weight):
                # we haven't gone over weight! possible solution found!
                happiness = max(sorted_items[item1][1] +
                                sorted_items[item2][1] +
                                sorted_items[item3][1], happiness)

print(happiness)