4

输入数据:权重列表。

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

例如:

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

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

4

1 回答 1

2

嘿...看起来你在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)
于 2013-06-29T14:54:50.890 回答