2 ms·
It 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 larg
by Veedrac 11y ago
It 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.