当前位置: 代码迷 >> python >> 在python中查找字符串的字谜
  详细解决方案

在python中查找字符串的字谜

热度:34   发布时间:2023-07-14 08:59:18.0

我为anagrams写了代码,但它没有给出一些测试用例的结果

import itertools
def find_all_anagrams(words, word):
        if word is None:
            return []
        else:
            m = set()
            for permutation in itertools.permutations(word.lower()):
                m.add("".join(permutation))
            ls = []
            for anagram in m:
                ls.append(anagram)
            n = [i for i in words if i in ls]
            return n
        pass

assert ["not", "ton"] == find_all_anagrams(["ant", "not", "ton"], "ont")
assert ["ant", "tan"] == find_all_anagrams(["ant", "not", "ton", "tan"], "tan")
assert [] == find_all_anagrams(["ant", "not", "ton", "tan"], "abc")
assert [] == find_all_anagrams(["ant", "not", "ton", "tan"], None)
assert [] == find_all_anagrams(None, None)
assert ["ant", "tan"] == find_all_anagrams(["ant", "not", "ton", "tan"], "TAN")

但对于这个测试用例,它给出了一个空列表

assert ["Ant", "Tan"] == find_all_anagrams(["Ant", "not", "ton", "Tan"], "TAN")

检查我的代码

这是一个字母问题; 如果你把所有wordswords小写,那么它的工作原理是:

>>> find_all_anagrams(["ant", "not", "ton", "tan"], "TAN")
['ant', 'tan']

您可以按如下方式最低限度地修改您的功能:

return [i for i in words if i.lower() in ls]

(注意不需要分配给n )。 现在它提供了您期望的输出:

>>> find_all_anagrams(["Ant", "not", "ton", "Tan"], "TAN")
['Ant', 'Tan']