问题:
给你一个整数权重列表。您需要将这些权重分配到两组中,以使每组总权重之间的差异尽可能小。
输入数据:权重列表。
输出数据:代表最小可能重量差异的数字。
我看到了答案,但我不明白为什么 bestval = -1。谁能帮我弄清楚?多谢!
代码如下:
import itertools;
def checkio(stones):
total = 0
for cur in stones:
total += cur
bestval = -1
for i in range(0,len(stones)):
for comb in itertools.combinations(stones,i):
weight = 0
for item in comb:
weight += item
d = diff(total - weight, weight)
if bestval == -1 or d < bestval:
bestval = d
return bestval
def diff(a,b):
if a >= b:
return a - b
else:
return b - a