How to calculate the number representing the smallest possible weight difference

Input: list of weights.

Output: A number representing the smallest possible weight difference.

for 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" 

this is my code:

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

but the code is not working, please help me! thank you very much!

+4
source share
1 answer

Heh ... it looks like you are cheating http://www.checkio.org/ :)

In any case, here the (working) solution is sent:

 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) 

Good, because your question was about fixing the code, here is another version based on what you posted:

 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 the sum of "what left", members of the list no in the choosen sum n = s - m # we want the difference between the two return abs(n - m) 
+2
source

Source: https://habr.com/ru/post/1488868/


All Articles