[Python]华为面试题,交换两个数组的元素使之总和的差值最小。

这是个NPC问题,所以就用穷举发了,在这里给出了一个用python的itertools的解法,个人认为比较简洁。
import itertools

def funcProduct(a, b):
    for c in itertools.permutations(b):
        for d in itertools.product(*[list(itertools.permutations(x)) for x in zip(a, c)]):
            yield zip(*d)

a = [1,2,3,4]
b = [5,6,700,800]
print min(funcProduct(a,b), key=lambda x:abs(sum(x[0])-sum(x[1])))

你可能感兴趣的:(C++,c,面试,python,华为)