How to divide a set into two subsets such that difference between the sum of numbers in two sets is minimal?

前端 未结 18 744
攒了一身酷
攒了一身酷 2020-11-27 10:55

Given a set of numbers, divide the numbers into two subsets such that difference between the sum of numbers in two subsets is minimal.

T

18条回答
  •  一个人的身影
    2020-11-27 11:43

    Combinations over combinations approach:

    import itertools as it
    
    def min_diff_sets(data):
        """
            Parameters:
            - `data`: input list.
            Return:
            - min diff between sum of numbers in two sets
        """
    
        if len(data) == 1:
            return data[0]
        s = sum(data)
        # `a` is list of all possible combinations of all possible lengths (from 1
        # to len(data) )
        a = []
        for i in range(1, len(data)):
            a.extend(list(it.combinations(data, i)))
        # `b` is list of all possible pairs (combinations) of all elements from `a`
        b = it.combinations(a, 2)
        # `c` is going to be final correct list of combinations.
        # Let's apply 2 filters:
        # 1. leave only pairs where: sum of all elements == sum(data)
        # 2. leave only pairs where: flat list from pairs == data
        c = filter(lambda x: sum(x[0])+sum(x[1])==s, b)
        c = filter(lambda x: sorted([i for sub in x for i in sub])==sorted(data), c)
        # `res` = [min_diff_between_sum_of_numbers_in_two_sets,
        #           ((set_1), (set_2))
        #         ]
        res = sorted([(abs(sum(i[0]) - sum(i[1])), i) for i in c],
                key=lambda x: x[0])
        return min([i[0] for i in res])
    
    if __name__ == '__main__':
        assert min_diff_sets([10, 10]) == 0, "1st example"
        assert min_diff_sets([10]) == 10, "2nd example"
        assert min_diff_sets([5, 8, 13, 27, 14]) == 3, "3rd example"
        assert min_diff_sets([5, 5, 6, 5]) == 1, "4th example"
        assert min_diff_sets([12, 30, 30, 32, 42, 49]) == 9, "5th example"
        assert min_diff_sets([1, 1, 1, 3]) == 0, "6th example"
    

提交回复
热议问题