Group Anagrams
Hard · 75 XPGroup words that are anagrams of each other. Print one line per group: the sorted words joined by spaces, groups ordered by first appearance.
Target output
ate eat tea nat tan bat
Blank · autosaved
PYgroup-anagrams.py
The sorted letters of a word make a key every anagram shares: "".join(sorted(word)).
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
groups = {}
for word in words:
groups.setdefault("".join(sorted(word)), []).append(word)
for key, group in groups.items():
print(" ".join(sorted(group)))
Run your code to check it…