gpt4 book ai didi

python - 如何计算代表最低可能重量差异的数字

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:51 25 4
gpt4 key购买 nike

输入数据:权重列表。

输出数据:代表最小可能重量差异的数字。

例如:

assert checkio([10, 10]) == 0, "1st example"
assert checkio([10]) == 10, "2nd example"
assert checkio([5, 8, 13, 27, 14]) == 3, "3rd example"
assert checkio([5, 5, 6, 5]) == 1, "4th example"
assert checkio([12, 30, 30, 32, 42, 49]) == 9, "5th example"
assert checkio([1, 1, 1, 3]) == 0, "6th example"

这是我的代码:

import random
def checkio(data):
for i in range(1,k):
half_sum = (reduce(lambda x,y:x+y,data))/2
k = len(data)
return min(lambda a:a >= half_sum,map(sum(random.sample(data,i))))

但是代码不起作用,请帮助我!非常感谢!

最佳答案

嘿...看起来你在欺骗http://www.checkio.org/ :)

无论如何,这里是提交的(工作)解决方案:

def checkio(stones):
def subcheckio(stones, left, rite):
if len(stones) == 0:
return abs(left - rite)

scores = []
nstones = stones[1:]
scores.append(subcheckio(nstones, left + stones[0], rite))
scores.append(subcheckio(nstones, left, rite + stones[0]))

return min(scores)

return subcheckio(stones, 0, 0)

好的,因为你的问题是关于修复你的代码,这里是基于你发布的内容的另一个版本:

import itertools

def checkio(data):
s = reduce(lambda x,y:x+y,data) # s is the sum, you don't need a loop
half_sum = s / 2

# instead of random.sample, using itertools to find all possible combinations
# of all possibles lenghts
perms = []
for i in range(len(data) + 1):
p = itertools.combinations(data, i)
perms += p

# min of a list comprehension to find the minimal sum >= half_sum
m = min([a for a in map(sum, perms) if a >= half_sum])
# that's the sum of "what's left", members of the list no in the choosen sum
n = s - m
# we want the difference between the two
return abs(n - m)

关于python - 如何计算代表最低可能重量差异的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com