Pybites Logo

Group anagrams

Level: Intermediate (score: 3)

As defined by the OED, an anagram is a word, phrase, or name formed by rearranging the letters of another.

Given a list of strings, return a list with any anagrams grouped together into sub-lists.

Example:

>>> from  anagram import group_anagrams
>>> anagrams = ["eat", "tea", "tan", "ate", "nat", "bat"]
>>> group_anagrams(anagrams)
[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

Example 2:

>>> from  anagram import group_anagrams
>>> anagrams = ["bat", "tab", "bad", "dab", "nat", "tan"]
>>> group_anagrams(anagrams)
[["bad", "dab"], ["bat", "tab"], ["nat", "tan"]]

Learner's Task

Your task is to write a function which:

- Takes a list of strings as input.

- Groups any anagrams among them further into sub-lists.

- Returns the grouped anagrams as a list containing lists containing strings.

Assumptions:

- You do not need to perform validation to determine whether the list does, in fact, contain anagrams.

- Any non-anagram should also go in its own sub-list (of one)

- Within the returned list, the anagrams can be in any order, i.e., the following are equally valid:

    [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
    [['bat'], ['eat', 'tea', 'ate'], ['tan', 'nat']]

Hints:

- There are different ways to solve this problem

- One way is to use Python's collections module, specifically defaultdict.

Keep calm and code in Python!