【发布时间】:2014-08-25 21:10:22
【问题描述】:
我正在尝试编写一个程序来比较两个单词列表并检查单词以查看它们是否是字谜。
例如,
输入:['cinema','host','aab','train'], ['iceman', 'shot', 'bab', 'rain']
我正在使用以下代码:
#!/usr/bin/env python
anagram_dict = {}
def anagram_solver(first_words,second_words):
for word in first_words:
first_word = list(word)
second_word = list(second_words[first_words.index(word)])
first_copy = first_word
second_copy = second-word
if len(first_word) != len(second_word):
anagram_dict[first_words.index(word)] = 0
else:
for char in first_word:
second_word = second_copy
if char in second_word:
first_copy.remove(char)
second_copy.remove(char)
else:
pass
if len(first_copy) == len(second_copy):
print first_copy
print second_copy
anagram_dict[first_words.index(word)] = 1
else:
anagram_dict[first_words.index(word)] = 0
for k,v in anagram_dict.items():
print "%d : %d" %(k,v)
if __name__ == "__main__":
anagram_solver(['cinema','host','aab','train'],['iceman','shot','bab','rain'])
当我执行此脚本时,在 for 循环 for char in first_word: 中,循环被一个列表项跳过。例如,如果它正在处理列表['c','i','n','e','m','a']
它只处理'c','n','m' 并忽略其他项目。如果我删除 list.remove(),那么它不会跳过项目。
人们可以执行这个脚本来更好地理解我在这里试图解释的内容。
只是想知道为什么会出现这种行为以及如何克服这个问题?
【问题讨论】:
-
另外,请评论,处理此问题的有效方法(字谜检查)。
-
为了高效的字谜检查,请注意
sorted('host') == sorted('shot')。 -
为了有效地处理这个问题,你应该为每个单词建立一个规范的表示。然后使用
==简单地比较它们。最明显的规范表示,是按字母顺序对每个单词的字母进行排序(正如@jonrsharpe 54 秒前写的那样。aDmw it!)
标签: python python-2.x