Easy: Warm-Ups · Problem 10 of 82

Compare Two Lists with Sets

EasyDictionaries and SetsPython

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:

  1. the names in both lists,
  2. the names only in a,
  3. 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}?

  1. {2, 3}
  2. {1, 4}
  3. {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)).)