checkio的日子(3)_第1张图片

这道题目纠结啊,各种想不出啊,算法啊有木有,不过看了一下老外的解法,觉得还是有点可以改进的。

from itertools import combinations
def checkio(batteries):
   min_diff = max(batteries)
   for combination_length in range(len(batteries)):
       for variant in combinations(batteries, combination_length):
           diff = abs(2 * sum(variant) - sum(batteries))
           min_diff = diff if min_diff > diff else min_diff
           check.append(min_diff)
           if min_diff == 0:
               break
       if min_diff == 0:
           break            
   return min_diff
if __name__ == "__main__":
   print checkio([5,5,6,5])
   print checkio([10,10])