【问题标题】:finding anagrams of a string in python在python中查找字符串的字谜
【发布时间】:2014-04-13 19:06:26
【问题描述】:

我为字谜编写了代码,但它没有给出某些测试用例的结果

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")

检查我的代码

【问题讨论】:

    标签: python string


    【解决方案1】:

    这是一个字母大小写问题;如果您将所有words 设为小写,则可以:

    >>> 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']
    

    【讨论】:

      猜你喜欢
      • 2013-03-04
      • 2021-12-12
      • 2020-10-28
      • 2017-01-16
      • 1970-01-01
      • 2015-12-27
      • 2020-11-08
      • 2016-06-24
      • 2012-02-16
      相关资源
      最近更新 更多