Anagram 解决 python 错误
我写了一个字谜求解算法,但不起作用。
for word in wordlist: #Checking for equal length
if sorted(word.replace("\n", "")) == sorted(anagram):
possible.append(word)
我需要使用 len(word) - 1 来去掉 \n。
I have written an anagram solving algorithm, which does not work.
for word in wordlist: #Checking for equal length
if sorted(word.replace("\n", "")) == sorted(anagram):
possible.append(word)
I needed to use len(word) - 1 to take away the \n.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(1) 我不明白第一个循环中“len(word)-1”中的“-1”。
(2) 你的第二个循环有几个问题:
它不检查字母是否相同,而是检查字谜中的每个字母是否在单词中。您没有使用计数信息,因此无法区分 bok 和 book。您还从正在迭代的序列中删除,这会导致意外的行为。
就我而言,我只是使用
而不是显式的 for 循环。
请注意,对单词进行排序是一种规范化过程——它确保任意两个互为字谜的单词具有相同的格式。确定两个事物是否是字谜词的另一种方法是确保字母计数相同:
(1) I don't understand the "-1" in "len(word)-1" in your first loop.
(2) Your second loop has several problems:
It doesn't check to see whether the letters are the same, it checks to see whether each letter in the anagram is in the word. You're not using the count information, so you can't distinguish between bok and book. You're also removing from a sequence you're iterating over, which leads to unexpected behaviours.
For my part I'd simply use
rather than explicit for loops.
Note that sorting the words is a kind of canonicalization process -- it makes sure that any two words which are anagrams of each other will be in the same format. Another approach to determine whether two things are anagrams would be to make sure that the letter counts are the same:
正如评论中提到的,我遇到的两个问题是:
possible.remove(word)
应该更改。像这样的东西怎么样:
对使用的工具的引用:
As mentioned in the comments the two evils that jump out at me are:
possible.remove(word)
should be changed.What about something like this:
References to tools used: