Feb 27, 2023
It is two lines in Python:
from collections import Counter
print(sorted(((v, k) for k, v in Counter(open(fname).read().split()).items()), reverse=True)[:n])
(Yes, I tested it.)
Using Counter
is standard for this sort of thing. It was introduced in Python 3.1 in 2009: doing without adds just one line (two more lines of code, one less line of import
).