面试题

'''
1,给一个不重复的整数数组A,同时给一个定值K,找出A中所有能组成和为K的所有组合,若没有则给出最接近的数的集合
'''

from itertools import combinations

def get_sum(tmpls):
    sum = 0
    for v in tmpls:
        sum+=v
    return sum

def calc(ls, value):
    result = []
    value_ls = []
    sum_ls = []
    count = len(ls)
    for i in range(1,count+1):
        for tmpls in combinations(ls, i):
            sum = get_sum(tmpls)
            if sum == value:
                result.append(list(tmpls))
            else:
                sum_ls.append(sum)
                value_ls.append(tmpls)
    if result==[]:
        sub_ls = list(map(lambda x: abs(x-value),sum_ls))
        v = min(sub_ls)
        pos = sub_ls.index(v)
        result.append(list(value_ls[pos]))

    return result


if __name__ == "__main__":
    ls = [1, 2, 3, 4, 5, 6]
    value = 6
    print(calc(ls, value))
    ls = [1, 4, 3, 4, 7, 8]
    value = 6
    print(calc(ls, value))

 

运行结果:

[[6], [1, 5], [2, 4], [1, 2, 3]]
[[7]]

你可能感兴趣的:(面试题解析)