$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · medium · #248

Which fix removes the bug?

from collections import defaultdict
counts = defaultdict(int, {'a': 1, 'b': 2})
if counts['zz'] > 0:
    print('zz seen')
print(len(counts))  # expected 2
  1. Compare with counts['zz'] >= 1
  2. Use defaultdict(list, ...)
  3. Wrap it in try/except KeyError
  4. Read with counts.get('zz', 0)
Indexing a defaultdict with a missing key inserts it with the default, so just reading counts['zz'] adds a third key. get() reads without inserting.
Play Problem Solving ▸