4 ms·
Counter is a lot slower though because it uses a heap underneath.
by lqdc13 11y ago
Counter is a lot slower though because it uses a heap underneath.
- Veedrac 11y agoIt doesn't - it directly inherits dict. I'm wrong, though; the optimizations Counter applies only make it faster when each `update` takes an iterable of a large number of elements. This is unlikely to happen in our case. You can actually bypass the Counter wrapper and use its accelerator directly: from _collections import _count_elements def wc(path): d = {} with open(path, "rb") as f: for line in f: _count_elements(d, line.split()) return sum(d.values()) However, this uses implementation details and is as such bad code.
- lqdc13 11y agoYup, I just checked. They're only using heap for most common. Nevertheless, defaultdict == win for counting things like if we actually wanted unique words in this case.