Learning Python via a little word frequency program
Ant
antroy at gmail.com
Wed Jan 9 06:40:05 EST 2008
> I'm interested to learn how more experienced Python folks would solve
> this little problem.
I think I'd do the following:
from collections import defaultdict
names = "freddy fred bill jock kevin andrew kevin kevin jock"
freq = defaultdict(lambda: 0)
for name in names.split():
freq[name] += 1
pairs = [(v, k) for k, v in freq.iteritems()]
for v, k in reversed(sorted(pairs)):
print "%-10s: %d" % (k, v)
defaultdict makes the frequency accumulation neater.
reversed(sorted(pairs)) avoids the little -v hack and makes it more
obvious what you are doing. Of course this could also be achieved by
doing pairs.sort() and pairs.reverse() before iterating over the pairs
list.
Cheers,
--
Ant.
More information about the Python-list
mailing list