2 ms·
Always fun writing compact Python: import sys from collections import Counter cnt = Counter([n.strip() for n in sys.stdin.readlines()])
by joshvm 10y ago
Always fun writing compact Python:
import sys
from collections import Counter
cnt = Counter([n.strip() for n in sys.stdin.readlines()])
for key, val in cnt.most_common():
print(val, key)
This isn't just playing code golf, it goes with point (2) - awesome libraries. One of the joys and curses with Python is finding the Pythonic ways to do things that you've hamfistedly written your own way for months.
- aidos 10y agoAnd you can actually ditch the list comprehension and put it directly in the function call! Counter(x for x in y)
- masklinn 10y agoFWIW the Counter line can be simplified slightly: cnt = Counter(n.strip() for n in sys.stdin) * no need for a list comprehension, a generator expression will do * file objects are iterable, and iterated line-wise