Skip to main content
 首页 » 编程设计

python之Python 中的 Anagram 检查

2025年05月04日11shihaiming

我正在尝试编写一个程序来比较两个单词列表并检查这些单词是否是变位词。

例如,

输入:['电影院','主持人','aab','火车'], ['冰人', '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(),那么它不会跳过项目。

可以执行此脚本以更好地理解我在这里试图解释的内容。

只是想知道为什么会出现这种行为以及如何克服这种情况?

请您参考如下方法:

您可以简单地对单词进行排序并检查它们是否相等:

def anagram_solver(first_words, second_words): 
    result = [] 
    for i in xrange(len(first_words)): 
        a = list(first_words[i]) 
        b = list(second_words[i]) 
        a.sort() 
        b.sort() 
         
        result.append(a == b) 
    return result 

例子:

>>> a = ['cinema','host','aab','train'] 
>>> b = ['iceman', 'shot', 'bab', 'rain'] 
>>> anagram_solver(a, b) 
 
[True, True, False, False]