You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于WUBRG双字母组合生成指定三字母组合的代码问题排查

问题修复:从双字母组合字典生成指定三字母组合

需求说明

接收由字母WUBRG组成的双字母组合输入字典,从中生成指定范围内的三字母组合并添加到字典中。指定的三字母组合集合为:
{'WBG', 'RGW', 'GUR', 'WUB', 'URW', 'RWB', 'GWU', 'UBR', 'BGU', 'BRG'}

示例

  • 输入:{'WU': 6, 'WB': 15, 'UB': 12}
  • 预期输出:{'WU': 6, 'WB': 15, 'UB': 12, 'WUB': 1}

当前实现代码

def generate_combinations():
    colors = ['W', 'U', 'B', 'R', 'G']
    combinations = [a + b + c for a in colors for b in colors for c in colors]
    return set(combinations)

def find_viable_combinations(input_dict, number):
    output_dict = input_dict.copy()
    three_color_combinations = generate_combinations()

    for combo in three_color_combinations:
        # Check if the combination can be formed using the 2-color combinations in input_dict
        can_form = all(color in input_dict for color in combo)

        if can_form:
            output_dict[combo] = number
    return output_dict

问题现象

运行上述代码后仅返回原输入字典,未添加任何指定的三字母组合。


问题排查与修复

核心问题点

  1. 三字母组合范围错误:generate_combinations()生成了所有可能的三字母组合(共125种),而非需求指定的10种目标组合,完全偏离了需求范围。
  2. 判断逻辑完全错误:all(color in input_dict for color in combo)是检查三字母组合中的单个字母是否存在于输入字典的键中,但输入字典的键是双字母组合(比如WU、WB),单个字母不可能出现在键里,导致判断永远为False,无法添加任何组合。

正确的判断逻辑应为:检查目标三字母组合的所有连续双字母子串是否都存在于输入字典中(比如WUB需要WU和UB都在输入里)。

修复后的代码

# 固定需求指定的三字母组合集合
TARGET_THREE_COMBOS = {'WBG', 'RGW', 'GUR', 'WUB', 'URW', 'RWB', 'GWU', 'UBR', 'BGU', 'BRG'}

def find_viable_combinations(input_dict, number):
    output_dict = input_dict.copy()
    
    for combo in TARGET_THREE_COMBOS:
        # 提取三字母组合的两个连续双字母子串
        required_pairs = [combo[:2], combo[1:]]
        # 检查所有必要的双字母组合是否都在输入字典中
        if all(pair in input_dict for pair in required_pairs):
            output_dict[combo] = number
    return output_dict

验证效果

调用find_viable_combinations({'WU': 6, 'WB': 15, 'UB': 12}, 1),会返回预期结果:
{'WU': 6, 'WB': 15, 'UB': 12, 'WUB': 1}


内容的提问来源于stack exchange,提问作者Jake Henderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:15:23