Python中字谜求解错误

0 投票
2 回答
692 浏览
提问于 2025-04-17 10:15

我写了一个用来解决字谜(变位词)的算法,但它没有正常工作。

for word in wordlist: #Checking for equal length
    if sorted(word.replace("\n", "")) == sorted(anagram):
        possible.append(word)

我需要用 len(word) - 1 来去掉换行符(\n)。

2 个回答

1

在评论中提到的两个问题让我觉得很重要:

  1. 为什么要写:if len(word) - 1 == len(anagram)?
  2. 在遍历一个列表的时候去修改它是个大忌。那行 possible.remove(word) 应该改一下。

那这样做怎么样:

anagramLength = len(anagram) # Get the value once to save CPU
possible1 = [word for word in wordlist if len(word)-1 == anagramLength] # List iteration
possible2 = [] # Make a new list that will be more constricted
for word in possible: #Checking for same letters
    for letter in anagram:
        if letter not in word:
            break
    else:
        possible2.append(word) # Only called if you don't break the above for loop

使用到的工具参考:

  1. 列表遍历
  2. for..else
7

(1) 我不太明白你在第一个循环中提到的“len(word)-1”是什么意思。

(2) 你的第二个循环有几个问题:

它没有检查字母是否相同,而是检查每个字母是否在单词中。你没有使用计数的信息,所以无法区分“bok”和“book”。而且你在遍历一个序列时还在删除元素,这会导致一些意想不到的情况发生。

就我而言,我会简单地使用

sorted_anagram = sorted(anagram)
possibles = [word for word in wordlist if sorted(word) == sorted_anagram]

而不是明确的for循环。

注意,排序单词是一种标准化的过程——它确保任何两个互为字谜的单词会以相同的格式出现。判断两个东西是否是字谜的另一种方法是确保字母的数量是相同的:

>>> from collections import Counter
>>> Counter('book')
Counter({'o': 2, 'k': 1, 'b': 1})
>>> Counter('obko')
Counter({'o': 2, 'k': 1, 'b': 1})
>>> Counter('bok')
Counter({'k': 1, 'b': 1, 'o': 1})
>>> 
>>> Counter('book') == Counter('boko')
True
>>> Counter('book') == Counter('bok')
False

撰写回答