A Python Puzzle

A few months ago, while refreshing my Python knowledge, I came up with this little puzzle; Given a collections.defaultdict, how can you have it use a counter for the defaults, i.e. 1 for the first lookup that’s not found, 2 for the second, etc? At the time I also wanted to learn about Jupyter notebooks, so I made a notebook with the puzzle and my solutions (I found five) and put it up on GitHub. Some time after I also posted the puzzle to Reddit to see if anyone would come up with additional solutions… nobody did, but they did find a few ways to turn some of the five solutions into one-liners which I added to the notebook.

Finding solutions to the puzzle is not hard, although finding all five will take some thinking. Simple though it is, this puzzle is a useful exploration of the ways you can encapsulate non-local state in Python.

The notebook with the solutions is here.