问题:
您将得到一个整数权重列表。您需要将这些权重分配到两个集合中,以使每个集合的总权重之间的差异尽可能小。
输入数据:权重列表。
输出数据:一个数字,表示可能的最小重量差。
我看到了一个答案,但我不明白为什么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
守候你守候我
呼啦一阵风
相关分类