直接上代码,可能还能优化吧
import itertools
def get_result(hope, list1):
"""
:param hope: # 期望相加所得参数
:param list1: # 所有数值
:return:
"""
result = [] # 结果列表
decimals_num = len(str(hope).split(".")[1])
for i in range(1, len(list1) + 1):
iter = itertools.combinations(list1, i) # 求每个长度的组合
group_item = list(iter)
for x in range(0, len(group_item)):
if round(sum(group_item[x]), decimals_num) == hope:
result.append(group_item[x])
print('有', len(result), '种情况得出结果为', hope, ',组合是', result)
if __name__ == '__main__':
get_result(23.7, [10.2, 13.5, 20.3, 40.1, 15.8, 7.9, 5, 18.7, 3, 0.7, 13, 7])
结果为
结果.png
网友评论