avatar Bite 374. Group Anagrams

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!

Login and get coding
go back Intermediate level
Bitecoin 3X

15 out of 16 users completed this Bite.
Will you be Pythonista #16 to crack this Bite?
Resolution time: ~31 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 5.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help