by MatmaRex · 3y ago · 0 comments
from collections import defaultdict
m = defaultdict(int)
m["nonexistent"]
len(m) # => 1
There are examples of the opposite too, though. Ruby's Hash does not insert the entry: m = Hash.new(0)
m["nonexistent"]
m.length # => 0It does if you initialise the hash with a block to do so:
m = Hash.new {|h, k| h[k] = 0}
m["nonexistent"]
m.length # => 1
That is, essentially, what defaultdict does. Just through subclassing (because `dict` does not provide such a fallback, but it has a magic method you can override to customise the mapping's behaviour in that case).if norvig isn't smart enough to use defaultdict without introducing bugs then i'm not either
(I am sure I never reported anything about the sudoku solver, since I never studied it.)