Sets · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
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 ✓ Passed
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.
def common(*iterables):
result = set()
for it in iterables:
result = result & set(it)
return result
def test_two_lists():
"""two lists with repeats"""
assert common([1, 2, 2, 3], [2, 3, 3, 4]) == {2, 3}, common([1, 2, 2, 3], [2, 3, 3, 4])
def test_many_kinds():
"""mixed iterable types"""
assert common('python', 'typhoon', ('t', 'h', 'x', 'o')) == {'t', 'h', 'o'}
def test_generator():
"""works with a generator argument"""
assert common(range(10), (n * 2 for n in range(10))) == {0, 2, 4, 6, 8}
def test_single():
"""a single iterable gives its distinct elements"""
assert common([3, 1, 3]) == {1, 3}
def test_none():
"""no arguments gives an empty set"""
assert common() == set()
def test_disjoint():
"""disjoint inputs give an empty set"""
assert common([1, 2], [3, 4], [1, 3]) == set()
def test_no_mutation():
"""arguments are not modified"""
a, b = {1, 2, 3}, {2, 3, 4}
common(a, b)
assert a == {1, 2, 3} and b == {2, 3, 4}
def test_returns_set():
"""returns a set"""
assert type(common([1], [1])) is set
Hints (2)
- Starting from an empty set and intersecting can only ever give an empty set. Start from the first iterable instead.
set.intersectionaccepts 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? ✓ Passed
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.
def dict_diff(old, new):
return {
'added': set(),
'removed': set(),
'changed': set(),
}
def test_example():
"""added, removed and changed keys"""
old = {'host': 'localhost', 'port': 8080, 'debug': True}
new = {'host': 'localhost', 'port': 9090, 'user': 'admin'}
r = dict_diff(old, new)
assert r == {'added': {'user'}, 'removed': {'debug'}, 'changed': {'port'}}, r
def test_identical():
"""identical dicts give three empty sets"""
d = {'a': 1, 'b': 2}
assert dict_diff(d, dict(d)) == {'added': set(), 'removed': set(), 'changed': set()}
def test_unhashable_values():
"""works with unhashable values"""
old = {'tags': ['a', 'b'], 'meta': {'x': 1}}
new = {'tags': ['a', 'b', 'c'], 'meta': {'x': 1}}
r = dict_diff(old, new)
assert r['changed'] == {'tags'}, r
assert r['added'] == set() and r['removed'] == set(), r
def test_empty_old():
"""everything is added when old is empty"""
assert dict_diff({}, {'a': 1, 'b': 2})['added'] == {'a', 'b'}
def test_types():
"""each entry is a set"""
r = dict_diff({'a': 1}, {'b': 2})
assert all(type(r[k]) is set for k in ('added', 'removed', 'changed')), r
assert r['removed'] == {'a'} and r['added'] == {'b'}
Hints (2)
- Keys views support set operations directly, for example
new.keys() - old.keys(). - 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 ✓ Passed
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.
def collect(pages, ignore, target):
for page in pages:
target = target | set(page)
target = target - set(ignore)
def pages():
yield ['Paris', 'Beijing', 'New York', 'London']
yield ['Cairo', 'New York', 'Milan']
yield ['Paris', 'Berlin']
def test_mutates():
"""the caller's set is updated"""
result = set()
collect(pages(), ['Paris', 'London'], result)
assert result == {'Beijing', 'New York', 'Cairo', 'Milan', 'Berlin'}, result
def test_keeps_existing():
"""existing elements of target are kept"""
result = {'Tokyo'}
collect(pages(), [], result)
assert 'Tokyo' in result and len(result) == 8, result
def test_ignore_missing():
"""ignoring items that never appeared is fine"""
result = set()
collect([['a', 'b']], ('z', 'a'), result)
assert result == {'b'}, result
def test_returns_none():
"""returns None"""
assert collect([[1]], [], set()) is None
def test_same_object():
"""target remains the same object"""
result = set()
before = id(result)
collect([[1, 2]], [2], result)
assert id(result) == before and result == {1}
Hints (2)
target = target | ...re-binds the local name and leaves the caller's set untouched. You need the in-place methods.updateanddifference_updateaccept 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 ✓ Passed
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).
def memoize(fn):
cache = {}
def inner(*args, **kwargs):
key = (args, tuple(kwargs.items()))
if key not in cache:
inner.calls += 1
cache[key] = fn(*args, **kwargs)
return cache[key]
inner.calls = 0
return inner
def make():
@memoize
def f(*args, **kwargs):
return sum(args) + sum(v * len(k) for k, v in kwargs.items())
return f
def test_basic_cache():
"""repeat calls hit the cache"""
f = make()
assert f(1, 2) == 3 and f(1, 2) == 3
assert f.calls == 1, f.calls
def test_kwarg_order():
"""keyword order does not matter"""
f = make()
r1 = f(a=1, bb=2)
r2 = f(bb=2, a=1)
assert r1 == r2 == 5
assert f.calls == 1, f"expected 1 real call, got {f.calls}"
def test_positional_order():
"""positional order still matters"""
f = make()
f(1, 2); f(2, 1)
assert f.calls == 2, f.calls
def test_mixed():
"""positional and keyword arguments together"""
f = make()
f(1, x=1, yy=2); f(1, yy=2, x=1); f(2, x=1, yy=2)
assert f.calls == 2, f.calls
def test_different_values():
"""different keyword values are different calls"""
f = make()
f(a=1); f(a=2)
assert f.calls == 2, f.calls
Hints (2)
tuple(kwargs.items())remembers the order the keywords were passed in. What hashable collection forgets order?- 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