简体   繁体   中英

finding anagrams of a string in python

i wrote the code for anagrams but it is not giving the result for some test cases

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

but for this test case it is giving an empty list

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

check my code

This is a letter case problem; if you make all the words lower-case, it works:

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

You can minimally modify your function as follows:

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

(note no need to assign to n ). Now it gives the output you expect:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM