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

Python从词典查找双单词组合变位词程序无输出问题求解

代码错误点

  • 变量名冲突:外层循环和内层循环都使用了a_word作为循环变量,外层的第一个候选词值会被内层循环覆盖,无法正确拼接两个不同的词
  • 候选词拼接逻辑错误:找到第一个候选词后,内层循环每匹配到一个符合条件的词就直接追加到candidate尾部,导致candidate会累计拼接多个词,永远无法刚好匹配两个词的字母计数
  • 无效冗余判断:通过拼接字符串再转Counter判断字母匹配的逻辑效率极低,且没有提前校验两个词的总长度和输入字符串长度相等的前置条件,浪费算力

修正后代码

from pathlib import Path
from collections import Counter

# 读取词典
with open(Path.home() / 'dictionary.txt', 'r', encoding='utf-8') as f:
    my_words = [line.strip().lower() for line in f if line.strip()]

print('Please type in your phrase:')
input_phrase = input().strip()
# 统计输入的字母计数(忽略空格、不区分大小写)
input_char_count = Counter(input_phrase.replace(' ', '').lower())
input_total_len = sum(input_char_count.values())
result = []

# 遍历第一个候选词
for word1 in my_words:
    count1 = Counter(word1)
    # 先过滤第一个词本身就超出输入字母计数的情况
    if any(count1[char] > input_char_count[char] for char in count1):
        continue
    # 计算剩余需要匹配的字母计数
    remaining_count = input_char_count - count1
    remaining_len = sum(remaining_count.values())
    # 遍历第二个候选词
    for word2 in my_words:
        # 提前过滤长度不匹配的
        if len(word2) != remaining_len:
            continue
        count2 = Counter(word2)
        if count2 == remaining_count:
            result.append(f"{word1} {word2}")

# 去重(不需要重复结果可保留,不需要可删除)
result = list(set(result))
print(result)

额外说明

  • 如果要避免输出room dirty和dirty room这类顺序相反的重复结果,可以在外层循环加索引,内层循环从外层当前索引的下一位开始遍历即可
  • 如果词典体量较大,建议提前给所有词典单词预存Counter和长度,避免循环中重复计算,提升运行效率

内容的提问来源于stack exchange,提问作者python noobie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:18:00