Compare Two Lists with Sets
Two teams signed up for a course. Write set_report(a, b) that takes two lists of names (which may contain repeats) and returns a tuple of three sorted lists:
- the names in both lists,
- the names only in
a, - the names only in
b.
set_report(["Ann", "Bob"], ["Bob", "Cy"]) is (["Bob"], ["Ann"], ["Cy"]).
Understand the problem
Learn the three set operators.
What is {1, 2, 3} & {2, 3, 4}? Type it as a set.
& is the intersection: the items in both sets, {2, 3}.
What is {1, 2, 3} - {2, 3, 4}?
- is the difference: the items of the left set that are not in the right one, {1}.
What is {1, 2, 3} ^ {2, 3, 4}?
{2, 3}{1, 4}{1, 2, 3, 4}
^ is the symmetric difference: items in exactly one of the two sets. Here 1 (only left) and 4 (only right). A union | would give {1, 2, 3, 4}.
Write the solution
Return a tuple of three sorted lists.
def set_report(a, b):
# Write your code here.
pass
Hint 1: a question to ask yourself
What happens to repeated names when you turn a list into a set? Why is that useful here?
Hint 2: the shape of the answer
Make set(a) and set(b). Use & for both, and - in each direction. Wrap each result in sorted(...): a set has no order, and the task asks for sorted lists.
Reflect
Solution
def set_report(a, b):
first, second = set(a), set(b)
return (sorted(first & second), sorted(first - second), sorted(second - first))
What this tests: set creation from a list (which removes repeats), the operators &, -, |, ^, and sorted to get a predictable order out of a set.
When to use sets: for membership ("is x in the group?") and for comparing groups. Both are much faster than loops over lists: x in a_set is O(1) on average, x in a_list is O(n).
Order is not defined: printing a set can show its items in any order, so return sorted(...) when order matters.
Cost: O(n + m) to build the sets; the operations are linear in the size of the sets.
What an interviewer might ask next: You have 100 teams. Which names are in every team? (set.intersection(*map(set, teams)).)
VISIBLE = 3
CASES = [
((['Ann', 'Bob'], ['Bob', 'Cy']), (['Bob'], ['Ann'], ['Cy']), 'one name in common'),
(([1, 2, 3], [2, 3, 4]), ([2, 3], [1], [4]), 'numbers'),
(([], []), ([], [], []), 'both empty'),
((['x', 'x', 'y'], ['y', 'y']), (['y'], ['x'], []), 'repeated names'),
((['a'], ['b']), ([], ['a'], ['b']), 'nothing in common'),
((['b', 'a'], ['a', 'b']), (['a', 'b'], [], []), 'the same names in another order'),
((['Zoe', 'amy', 'Bob'], []), ([], ['Bob', 'Zoe', 'amy'], []), 'sorted with capitals first'),
]