user3397770
user3397770

Reputation: 17

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

Upvotes: 0

Views: 308

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122161

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

Upvotes: 2

Related Questions