3 ms·
Some quick points: * You need to loop over sys.argv[1:]. * You could use binary mode to avoid decoding (which the C++ avoids). * You could use collections.Co
by Veedrac 11y ago
Some quick points:
* You need to loop over sys.argv[1:].
* You could use binary mode to avoid decoding (which the C++ avoids).
* You could use collections.Counter() and its `update` method, which should be both cleaner and faster on Python 3:
d = Counter()
with open(path) as f:
for line in f:
d.update(line.split())
- lqdc13 11y agoCounter 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.
- raiph 11y agoFwiw, the same (I think) in idiomatic Perl 6: +$path.IO.lines.words