2013-06-29 5 views
4

입력 데이터 : 가중치 목록.가장 낮은 가능한 무게 차이를 나타내는 숫자를 계산하는 방법

출력 데이터 : 가능한 가장 작은 무게 차이를 나타내는 숫자입니다. exmaple에 대한

: 내 코드입니다

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

:) ok, 나는 할 것이다. 너의 생각이 내 것보다 낫다. – cedrichu

관련 문제