220. Python Program to Group Words That Are Anagrams
HardPhase 3 · Challenge
You know every tool here: sorted(), join() and a dictionary of lists. It takes a few steps, so try a short example on paper first.
Overview
Grouping anagrams is a well-known interview question. It shows how a dictionary can sort many things into groups in one pass.
Problem Statement
Kenji runs a word-game club and wants to put words that are anagrams into groups.
Two words are anagrams when they have the same letters, the same number of times, in any order. For example, eat, tea and ate are anagrams.
Read a line of words. Print each group on its own line:
- The groups come in the order of their first word in the input.
- Inside a group, the words keep their input order.
- Put one space between the words.
- A word with no anagram partner is a group of its own.
Examples
Example 1. Input eat tea tan ate nat bat gives:
eat tea ate
tan nat
bat
Why: eat, tea and ate all have the letters a, e and t. tan and nat both have a, n and t. bat has no partner, so it is a group of one.
Example 2. Input listen pots silent stop tops gives:
listen silent
pots stop tops
Why: listen is the first word, so its group comes first. pots is the first word of the second group, so that group comes next.
Input
One line of words, with one space between them (1 word or more). Each word has small letters only, from a to z. No word appears twice. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each group, with one space between the words. The tests try 9 different inputs, also one word and words with no partner at all.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.