Group numbers by parity
Input
group_by([1,2,3,4,5], lambda x: x % 2)
Output
{1: [1, 3, 5], 0: [2, 4]}
Items are grouped into odd (1) and even (0); order within each list follows the input order.
Full lesson preview
Use collections.defaultdict to group items into lists keyed by a function.
Problem statement
Task
Examples
Input
group_by([1,2,3,4,5], lambda x: x % 2)
Output
{1: [1, 3, 5], 0: [2, 4]}
Items are grouped into odd (1) and even (0); order within each list follows the input order.
Input format
Output format
Constraints
Samples
Input
group_by(["apple","apricot","banana"], lambda s: s[0])
Output
{'a': ['apple', 'apricot'], 'b': ['banana']}
Groups by first letter of each string.