如何修复Wordle复刻版中的重复黄色标记问题?
修复Wordle复刻程序中的重复黄色标记问题
你的代码在处理重复字符时逻辑有误,比如目标单词为paste、猜测单词为teeth时,无法正确标记重复的e。核心问题在于你没有统计目标单词中未被绿色匹配的字符剩余数量,导致重复字符被错误标记为黄色。
修复后的代码
from rich import print target_word = 'paste' solved = False word = input('Enter a word: ') n = 0 while n < 6 and not solved: hw = [""] * 5 # 统计目标单词中各字符的出现次数 target_char_count = {} for char in target_word: target_char_count[char] = target_char_count.get(char, 0) + 1 # 第一步:处理绿色匹配 for i in range(5): if word[i] == target_word[i]: hw[i] = "[on green]" + word[i] # 匹配到绿色后,减少目标字符的剩余计数 target_char_count[word[i]] -= 1 # 第二步:处理黄色和白色 for i in range(5): if not hw[i]: # 还未标记绿色的位置 char = word[i] if target_char_count.get(char, 0) > 0: hw[i] = "[on yellow]" + char target_char_count[char] -= 1 else: hw[i] = "[on white]" + char print("".join(hw)) if word == target_word: solved = True else: word = input('Enter a word: ') n += 1 if solved: print(f"[on green]{target_word}") print(f'You got it in {n} tries') else: print(f"[on green]{target_word}") print("You didn't get it in 6 tries.")
关键修改说明
- 新增
target_char_count字典,统计目标单词中每个字符的初始出现次数,确保后续标记时能准确判断剩余可匹配的字符数量。 - 处理绿色匹配时,每匹配到一个字符就减少对应计数,避免后续黄色标记重复使用已被绿色匹配的字符配额。
- 处理黄色标记时,仅当目标中还有剩余的该字符时才标记黄色,否则标记白色,彻底解决重复字符的错误标记问题。
测试你提到的场景:目标paste、猜测teeth,会输出正确的标记效果:[on white]t[on yellow]e[on white]e[on green]t[on white]h。
内容的提问来源于stack exchange,提问作者Nico Ray
相关产品推荐
相关产品推荐

