Sets · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What is the type of x after x = {}?
2. What does this print?
s = set('mississippi')
print(len(s), sorted(s))
3. What does this print?
s1 = {1, 2, 3}
s2 = {3, 4}
print(len([*s1, *s2]), len({*s1, *s2}))
4. Which of these raises a TypeError?
5. What does this print?
s = {1, 2, 3}
s.discard(10)
try:
    s.remove(10)
except KeyError:
    print('KeyError', len(s))
6. What does this print?
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a - b), sorted(b - a), sorted(a ^ b))
7. What does this print?
a = {1, 2}
b = {3, 4}
print(a < b, a > b, a == b, a.isdisjoint(b))
8. What does this print?
s1 = {1, 2, 3, 4}
s2 = {2, 3}
s3 = {3, 4}
a = set(s1)
a -= s2 - s3
b = set(s1)
b.difference_update(s2, s3)
print(sorted(a), sorted(b))
9. What does this print?
a = {1, 2}
alias = a
a = a | {3}
b = {1, 2}
b_alias = b
b |= {3}
print(len(alias), len(b_alias))
10. What does this print?
fs = frozenset({'a', 'b'})
s = {'b', 'c'}
print(type(fs | s).__name__, type(s | fs).__name__, s & fs == fs & s)
11. What does this print?
d = {'a': 1, 'b': 2, 'c': 3}
e = {'b': 20, 'c': 3, 'd': 4}
print(sorted(d.keys() & e.keys()), sorted(d.items() & e.items()))
12. What happens here?
d = {'a': 1, 'b': 2, 'c': 3}
for k in d:
    d[k] = d[k] * 10
for k in d:
    if d[k] > 10:
        del d[k]

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Common to all

Write common(*iterables) that returns a set of the elements that appear in every iterable passed to it.

- The arguments can be any iterables (lists, tuples, strings, sets, generators…), and elements may repeat inside an iterable. - With no arguments, return an empty set. - Don't modify the arguments.

Hints (2)
  1. Starting from an empty set and intersecting can only ever give an empty set. Start from the first iterable instead.
  2. set.intersection accepts any number of iterables: set(first).intersection(*rest).
Show a solution
def common(*iterables):
    if not iterables:
        return set()
    first, *rest = iterables
    return set(first).intersection(*rest)

Exercise 2: What changed between two dicts?

Write dict_diff(old, new) that compares two dictionaries and returns a dictionary with three sets of keys:

- 'added': keys in new but not in old; - 'removed': keys in old but not in new; - 'changed': keys in both whose values differ.

Values may be unhashable (lists, dicts), so compare them with == rather than putting items() into set operations.

Hints (2)
  1. Keys views support set operations directly, for example new.keys() - old.keys().
  2. For 'changed', intersect the keys views and keep the keys whose values compare unequal.
Show a solution
def dict_diff(old, new):
    shared = old.keys() & new.keys()
    return {
        'added': set(new.keys() - old.keys()),
        'removed': set(old.keys() - new.keys()),
        'changed': {k for k in shared if old[k] != new[k]},
    }

Exercise 3: Collect, then filter, in place

Write collect(pages, ignore, target) that adds every item of every page in pages (an iterable of lists) to the existing set target, and then removes every item in ignore (any iterable).

It must mutate target (the caller's set) and return None. Items in ignore that never appeared must not cause an error.

Hints (2)
  1. target = target | ... re-binds the local name and leaves the caller's set untouched. You need the in-place methods.
  2. update and difference_update accept any iterable, so no conversion is needed.
Show a solution
def collect(pages, ignore, target):
    for page in pages:
        target.update(page)
    target.difference_update(ignore)

Exercise 4: A cache that ignores keyword order

Write a decorator memoize that caches a function's results so that the order of keyword arguments doesn't matter: f(a=1, b=2) and f(b=2, a=1) must share one cache entry. Positional arguments keep their order (f(1, 2) and f(2, 1) are different calls).

The decorated function should also expose the number of actual calls to the original function as an attribute calls (an int, starting at 0).

Hints (2)
  1. tuple(kwargs.items()) remembers the order the keywords were passed in. What hashable collection forgets order?
  2. Each keyword argument's name is unique, so frozenset(kwargs.items()) loses nothing but the order.
Show a solution
def memoize(fn):
    cache = {}
    def inner(*args, **kwargs):
        key = (args, frozenset(kwargs.items()))
        if key not in cache:
            inner.calls += 1
            cache[key] = fn(*args, **kwargs)
        return cache[key]
    inner.calls = 0
    return inner