Python乱序单词还原功能字母重复匹配错误如何修复
乱序单词匹配问题修复方案
问题核心
原代码仅校验字符是否存在,未校验字符的出现次数,因此输入包含重复字符的乱序词(如helol含2个l)时,只要候选词包含对应字符、长度匹配就会被误判,无论字符重复次数是否符合要求。
修复方案
使用Python标准库collections.Counter统计字符出现频率,直接对比频率即可精确匹配乱序词,同时优化原有逻辑的执行效率、补充资源释放处理。
修复后完整代码
import json from collections import Counter # 使用with上下文管理器自动关闭文件,避免资源泄漏 with open("data.json", encoding="utf-8") as f: word_lib = json.load(f) input_str = input("Enter a Jumbled word: ") # 提前统计输入字符的频率,避免循环中重复计算 input_counter = Counter(input_str) input_len = len(input_str) for candidate in word_lib: # 先判断长度,不匹配直接跳过,减少不必要的计算 if len(candidate) != input_len: continue # 对比字符频率,完全一致则输出 if Counter(candidate) == input_counter: print(candidate)
可选优化
如果需要忽略大小写、忽略候选词中的空格/特殊符号匹配,可以在统计Counter前增加预处理步骤:
# 示例:统一转小写,仅保留字母参与匹配 def get_counter(s): # 过滤非字母字符,统一转小写 processed = [c.lower() for c in s if c.isalpha()] return Counter(processed) input_counter = get_counter(input_str) input_letter_count = sum(input_counter.values()) for candidate in word_lib: candidate_counter = get_counter(candidate) if sum(candidate_counter.values()) != input_letter_count: continue if candidate_counter == input_counter: print(candidate)
内容的提问来源于stack exchange,提问作者Gaming with Akashdeep
相关产品推荐
相关产品推荐

