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

输入数据:权重列表.

输出数据:表示可能的最低权重差异的数字.

例如:

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)
点赞