多个数字组合相加的和最接近或等于某个数
# 方法一:利用python内置包itertools
from itertools import combinations
def min_combination(data: list, num: int):
"""
最小组合
:param data: 数组
:param num:
:return:
"""
res = []
_min = sum(data)
for i in range(2, len(data) + 1):
_iter = combinations(data, i)
for lt in _iter:
if abs(sum(lt) - num) < _min:
_min = abs(sum(lt) - num)
res = lt
return res
# 方法二:利用python的math包
import math
def min_combination(data: list, num: int):
"""
最小组合
:param data:
:param num:
:return:
"""
real_size = int(math.pow(2, len(data)))
_min = abs(sum(data) - num)
min_comb = []
for i in range(real_size):
min_list = []
total = 0
for j in range(len(data)):
if i & (1 << j):
min_list.append(data[j])
total = total + data[j]
if abs(total - num) <= _min:
if abs(total - num) == _min:
min_comb.append(min_list)
else:
min_comb = [min_list]
_min = abs(total - num)
if min_comb:
return min_comb[-1]
return min_comb