Anagram


1. The subject

Given an array of strings, return an array of strings that groups all anagrams. An anagram is a word that has the same letters, but in different positions. i.e. given ["cars", "thing", "scar", "dog", "god", "arcs", "the"] return [["cars", "scar", "arcs"], ["thing"], ["dog", "god"], ["the"]]


2. The train of thought

Sorting all the letters of each word produces a value that can be used as a dictionary key. For example, scar and cars get acRS. The value corresponding to the key is a list that stores the original words. Return a list of the dictionary values.

Another way to check if two words are aponymous is to convert them to a list and remove them.


3. The implementation

def find_anagrams(words) :
    words_pair = zip(words, [str(sorted(w)) for w in words])
    res_dict = {}
    for i, j in words_pair:
        res_dict.setdefault(j, [])
        res_dict[j].append(i)
    return list(res_dict.values())


words = ['cars'.'thing'.'scar'.'dog'.'god'.'arcs'.'the']
res = find_anagrams(words)
print(res)

"""
[['cars', 'scar', 'arcs'], ['thing'], ['dog', 'god'], ['the']]
"""

Copy the code

Completed in 2018.12.18