[Programming Pearls] Column 2 – Find anagrams

Problem:
Given a list of words, collect anagrams.

Solution:
For each word, generate its signature by sorting its chars. And then collect words with same signature.

Code:

def prog_2_C_find_anagrams(l):
    """
    >>> prog_2_C_find_anagrams(['spot', 'stop', 'tops', 'deal', 'lead'])
    defaultdict(<class 'list'>, {'opst': ['spot', 'stop', 'tops'], 'adel': ['deal', 'lead']})
    """
    from collections import defaultdict
    result = defaultdict(list)
    for word in l:
        word = word.lower()
        charlist = list(word)
        sorted_charlist = sorted(charlist)
        normalized_word = "".join(sorted_charlist)
        result[normalized_word].append(word)
    return result

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>