2013-06-29 20 views
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)))) 

但代码不能正常工作,请帮帮我!非常感谢!

+0

函数不应该是'min'的第一个参数。 –

+0

你的意思是两个重量之间可能的最小差异? – arshajii

+0

@LevLevitsky谢谢!我试图修复它.. – cedrichu

回答

2

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

反正这里是(工作)解决方案是submited有:

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

啊哈我试图解决我的答案 – cedrichu

+0

非常感谢!这真的很酷 – cedrichu

+0

:)好吧,我会的。你的想法比我的好 – cedrichu