问题描述
我为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")
检查我的代码
1楼
这是一个字母问题;
如果你把所有words
都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']