假设有这样一个字典{1.0: 5.0, 2.0: 6.0, 3.0: 10.0, 4.0: 5.0, 5.0: 10.0, 6.0: 8.0, 7.0: 7.0, 8.0: 6.0, 9.0: 2.0, 10.0: 3.0, 11.0: 2.0, 12.0: 3.0, 13.0: 5.0, 14.0: 8.0, 15.0: 5.0, 16.0: 4.0, 17.0: 4.0, 18.0: 2.0, 19.0: 4.0, 20.0: 4.0}
1、需求是将字典的值相加,值的总和介于15-30之间,列出字典的键健组合 例:1.0 2.0 3.0 键值总和是21 符合要求 1.0 2.0的键值总和11 不符合要求 输出的结果为[1.0,2.0,3.0] 这样的结果
2、键值重复率去重,重复率要小于等于50% 例: 第一个输出的列表为[1.0,2.0,3.0] 键值总和是21 其中[1.0,2.0]键值总和是12 第二个输出的[1.0,2.0,4.0]键值总和是16,其中[1.0,2.0]键值总和是12 =12/16占比大于50%,,这条结果就不予输出,[1.0,2.0,4.0,5.0]键值总和为26 占比小于=12/26 小于50% 这条结果就要输出 以此类推
def get_combinations(dictionary, target_sum):
keys = list(dictionary.keys())
combinations = []
# 递归生成所有可能的组合
def generate_combinations(curr_sum, curr_index, curr_combination):
if curr_sum == target_sum:
combinations.append(curr_combination)
return
if curr_sum > target_sum or curr_index >= len(keys):
return
# 包括当前键
generate_combinations(curr_sum + keys[curr_index], curr_index + 1, curr_combination + [keys[curr_index]])
# 不包括当前键
generate_combinations(curr_sum, curr_index + 1, curr_combination)
generate_combinations(0, 0, [])
return combinations
def filter_combinations(combinations, dictionary):
filtered_combinations = []
for combination in combinations:
value_sum = sum([dictionary[key] for key in combination])
value_ratio = value_sum / sum(dictionary.values())
if value_ratio <= 0.5:
filtered_combinations.append(combination)
return filtered_combinations
# 示例字典
dictionary = {1.0: 5.0, 2.0: 6.0, 3.0: 10.0, 4.0: 5.0, 5.0: 10.0, 6.0: 8.0, 7.0: 7.0, 8.0: 6.0, 9.0: 2.0, 10.0: 3.0,
11.0: 2.0, 12.0: 3.0, 13.0: 5.0, 14.0: 8.0, 15.0: 5.0, 16.0: 4.0, 17.0: 4.0, 18.0: 2.0, 19.0: 4.0, 20.0: 4.0}
# 获取键列表组合
combinations = get_combinations(dictionary, target_sum=15)
# 过滤符合条件的结果
filtered_combinations = filter_combinations(combinations, dictionary)
# 输出结果
for combination in filtered_combinations:
print(combination)
用chatgpt生成的这组结果测试了下 输出的组合方式不完整,缺少很多有效的组合