import itertools
def get_result(hope, list_input):
"""
:param hope: # 期望相加所得参数
:param list_input: # 所有数值
:return:
"""
def generate_combination(items, length):
for combination in itertools.combinations(items, length):
result_generate = list(combination)
# print(result)
yield result_generate
# 容差值,避免float计算过小
epsilon = 0.001
# 剔除大于目标值部分的列表内容不进行计算
larger_list = [i for i in list_input if i > hope]
step_1_list = list(set(list_input) - set(larger_list))
# 根据初步判断后的step_1_list,迭代每一种数据长度的可能性
result = []
for i in range(1, len(step_1_list) + 1):
# print('当前判断长度:' + str(i))
# 用迭代器 按照每种长度 生成每种可能
calculate = generate_combination(items=step_1_list, length=i)
# 循环迭代结果
for x in calculate:
# 对迭代器中每个元组求和
if abs(sum(x) - hope) <= epsilon:
result = x
# print('计算出', hope, ',组合是', result)
# 计算出结果,则该
break # 如果计算出结果,则终止对迭代结果循环
else:
# print('无结果')
continue # 未计算出结果,继续对迭代结果循环
break # if True 则终止对所有长度可能的循环
return hope, result
if __name__ == '__main__':
# 请在此输入求和值
aggregate = [10, 20, 30, 40, 50, 99999]
divisions = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 99998, 1]
for i in aggregate:
print(get_result(i, divisions))
标签:combination,迭代,Python,list,求和,result,input,hope
From: https://www.cnblogs.com/AZ26/p/18346045