Coding Exercises · Practice

Quiz & exercises

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

Quiz

1. What does this print?
from collections import Counter
c = Counter({'a': 1})
c.update({'a': 5, 'b': 2})
d = {'a': 1}
d.update({'a': 5, 'b': 2})
print(c['a'], d['a'])
2. What does this print?
from collections import Counter
c = Counter(x=1)
c.update(y=5)
print(list(c), c)
3. What does this print?
from collections import Counter
seeded = Counter(dict.fromkeys(['amber', 'blue'], 0))
a = seeded + Counter(['blue'])
seeded.update(['blue'])
print(dict(a), dict(seeded))
4. Why does ChainMap(dev, common)['database'] lose the port setting that only common defines?
5. What does this print?
from collections import ChainMap
env = {'db': {'user': 'test'}}
common = {'db': {'user': 'admin', 'port': 5432}}
chain = ChainMap(env, common)
chain['db'] = ChainMap(env['db'], common['db'])
print(type(env['db']).__name__, chain['db']['port'])
6. What does this print?
from collections import Counter
c = Counter('aabbbc')
print(dict(c.most_common()), c.most_common(1))

Coding exercises

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

Exercise 1: Exercise 1a: merge with defaultdict

Write merge(*dicts) that combines any number of word-frequency dictionaries into one plain dict with the total count of each word, sorted by count from highest to lowest. Words with equal counts keep the order in which they were first seen.

Accumulate the totals in a defaultdict. Don't modify the input dictionaries.

Hints (2)
  1. totals[word] += count works for new words too, because the defaultdict(int) supplies 0.
  2. sorted(totals.items(), key=lambda e: e[1], reverse=True) sorts the pairs by count; sorted is stable, so ties keep their order. Wrap it in dict(...).
Show a solution
from collections import defaultdict

def merge(*dicts):
    totals = defaultdict(int)
    for d in dicts:
        for word, count in d.items():
            totals[word] += count
    return dict(sorted(totals.items(), key=lambda e: e[1], reverse=True))

Exercise 2: Exercise 1b: merge with Counter

Solve the same problem with a Counter: merge(*dicts) returns a plain dict of total counts, sorted from highest to lowest (ties in first-seen order), without modifying the inputs.

Hint: a Counter's repr looks sorted, but its iteration order isn't.

Hints (2)
  1. Counter.update(mapping) adds the counts, which is exactly the merge.
  2. most_common() with no argument returns every pair sorted by count. Pass it to dict.
Show a solution
from collections import Counter

def merge(*dicts):
    totals = Counter()
    for d in dicts:
        totals.update(d)
    return dict(totals.most_common())

Exercise 3: Exercise 2: count eye colors, zeros included

Write count_eye_colors(persons, possible_eye_colors). Each person has an eye_color attribute. Return a mapping (a dict or Counter) with an entry for every color in possible_eye_colors, in that order, giving how many people have it. Colors nobody has must appear with 0.

People whose color isn't in possible_eye_colors are ignored.

Hints (2)
  1. A Counter only holds colors it has seen. Build the result by looping over possible_eye_colors instead.
  2. Looking up a missing key in a Counter returns 0, so {color: counts[color] for color in possible_eye_colors} fills in the zeros and ignores unknown colors.
Show a solution
from collections import Counter

def count_eye_colors(persons, possible_eye_colors):
    counts = Counter(p.eye_color for p in persons)
    return {color: counts[color] for color in possible_eye_colors}

Exercise 4: Exercise 3: layered settings with ChainMap

common.json, dev.json and prod.json are in the working directory.

1. Write chain_recursive(d1, d2) that returns a ChainMap in which d1 overrides d2, at every level: whenever a key holds a dict in both d1 and d2, its value in the result must be a chain_recursive of the two sub-dicts. 2. Write settings(env) that loads <env>.json and common.json and returns chain_recursive(env_settings, common_settings).

Don't build merged copies of the data: the result and its nested sections must be ChainMap objects.

Hints (2)
  1. A single ChainMap returns the whole sub-dict from the first map. Loop over d1.items() and look for values that are dicts in both maps.
  2. For each such key, store chain_recursive(d1[k], d2[k]) in the chain (chain[k] = ...), so the nested lookup is layered too.
Show a solution
import json
from collections import ChainMap

def load_settings(env):
    with open(f'{env}.json') as f:
        return json.load(f)

def chain_recursive(d1, d2):
    chain = ChainMap(d1, d2)
    for k, v in d1.items():
        if isinstance(v, dict) and isinstance(d2.get(k), dict):
            chain[k] = chain_recursive(v, d2[k])
    return chain

def settings(env):
    return chain_recursive(load_settings(env), load_settings('common'))