Group by letters
Two words belong together if one is a rearrangement of the other's letters, ignoring case. Group a list of words this way.
group_by_letters(
["stone", "cat", "notes", "act"])
# [["stone", "notes"], ["cat", "act"]]Groups appear in the order their first word appears, and words stay in their original order within a group.
Approach
Comparing every pair of words is slow. Find a key that is equal exactly when two words belong together, then let a dict do the grouping. Sorting a word's letters gives such a key: "stone" and "notes" both become "enost".
collections.defaultdict creates a list the first time you touch a key:
from collections import defaultdict
groups = defaultdict(list)
groups["k"].append(1)Dicts keep insertion order, which handles the group ordering for you.
Your task
Write group_by_letters(words) returning a list of groups as described. The word's original spelling is kept in the output.
The explanation opens here once every check passes.