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

Python开发Hangman游戏提示词过滤函数规则不生效问题求助

Hangman游戏候选词筛选代码问题修复

原代码核心问题

  • 无效类型转换:list(wrong_guess_lst) 转换后没有赋值给变量,后续按索引遍历集合会直接报错
  • 匹配逻辑倒置:仅在部分非下划线位置匹配时就添加单词,没有校验所有非下划线位置全部匹配的规则;只要某一个猜错字母不等于当前位置字符就通过校验,没有校验单词全字符都不在猜错列表的规则
  • 重复添加问题:同一个单词会因为多个匹配位置被多次加入结果列表

修正后的代码

def filter_words_list(words, pattern, wrong_guess_lst):
    """
    :param words: 主函数传入的待筛选单词列表
    :param pattern: 待匹配的单词模式,例如p__pl_
    :param wrong_guess_lst: 用户猜错的字母集合
    :return: 符合所有筛选条件的单词列表
    """
    pattern_len = len(pattern)
    wrong_guess = set(wrong_guess_lst) # 转集合实现O(1)存在性判断,效率更高
    words_suggestions = []
    for word in words:
        # 校验长度匹配
        if len(word) != pattern_len:
            continue
        # 校验所有非下划线位置和模式完全匹配
        pattern_match = True
        for p_char, w_char in zip(pattern, word):
            if p_char != '_' and p_char != w_char:
                pattern_match = False
                break
        if not pattern_match:
            continue
        # 校验单词不含任何猜错的字母
        if wrong_guess & set(word):
            continue
        # 所有条件满足才加入结果
        words_suggestions.append(word)
    return words_suggestions

更Pythonic的简化写法

def filter_words_list(words, pattern, wrong_guess_lst):
    pattern_len = len(pattern)
    wrong_guess = set(wrong_guess_lst)
    return [
        word for word in words
        if len(word) == pattern_len
        and all(p == '_' or p == w for p, w in zip(pattern, word))
        and not any(c in wrong_guess for c in word)
    ]

内容的提问来源于stack exchange,提问作者Mustang Sally

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:27:02