Group By
Write group_by(items, key) where key is a function. It returns a dictionary that maps each value key(item) to the list of items that produced it, in their original order.
group_by(["apple", "bean", "fig"], len) is {5: ["apple"], 4: ["bean"], 3: ["fig"]}.
Understand the problem
Functions can be passed as arguments.
What does list(map(len, ["apple", "bean"])) give? Type the list.
len is a function; map calls it on each item. The same idea works for your parameter key: you can call key(item) inside group_by.
What is key(item) when key is lambda n: n % 3 and item is 7?
7 % 3 is 1. The key function decides which group each item belongs to.
Write the solution
Return the dictionary of lists.
def group_by(items, key):
# Write your code here.
pass
Hint 1: a question to ask yourself
For each item, how do you find out its group, and how do you add the item to that group even when the group is new?
Hint 2: the shape of the answer
Loop over the items, compute key(item) and use setdefault(group, []).append(item).
Reflect
Solution
def group_by(items, key):
groups = {}
for item in items:
groups.setdefault(key(item), []).append(item)
return groups
Another way: defaultdict
from collections import defaultdict
def group_by(items, key):
groups = defaultdict(list)
for item in items:
groups[key(item)].append(item)
return dict(groups)
What this tests: higher-order functions (a function as a parameter), setdefault, and building groups.
This is itertools.groupby without the catch. itertools.groupby only groups neighbours, so you must sort by the key first. This dictionary version works on any order.
Used everywhere: group orders by customer, log lines by level, files by extension. In pandas it is df.groupby; in SQL, GROUP BY.
Cost: O(n) plus the cost of calling key n times.
What an interviewer might ask next: Make the groups hold only a field of each item, not the item. (Add a second function parameter value, or use a comprehension afterwards.)
VISIBLE = 3
CASES = [
('result = group_by(["apple", "bean", "fig", "kiwi"], len)', {5: ['apple'], 4: ['bean', 'kiwi'], 3: ['fig']}, 'group words by length'),
('result = group_by([1, 2, 3, 4, 5, 6], lambda n: n % 3)', {1: [1, 4], 2: [2, 5], 0: [3, 6]}, 'group numbers by remainder'),
('result = group_by([], len)', {}, 'no items'),
('result = group_by(["a", "b"], lambda s: "same")', {'same': ['a', 'b']}, 'everything in one group'),
('result = group_by(["Ann", "bob", "Cy", "dan"], lambda s: s[0].isupper())', {True: ['Ann', 'Cy'], False: ['bob', 'dan']}, 'a True and False key'),
('result = group_by([3, 1, 2, 1, 3], lambda n: n)', {3: [3, 3], 1: [1, 1], 2: [2]}, 'repeated items'),
('result = group_by([(1, "x"), (2, "y"), (1, "z")], lambda t: t[0])', {1: [(1, 'x'), (1, 'z')], 2: [(2, 'y')]}, 'tuples grouped by their first part'),
]