An introduction

This is a semi-public place to dump text too flimsy to even become a blog post. I wouldn't recommend reading it unless you have a lot of time to waste. You'd be better off at my livejournal. I also have another blog, and write most of the French journal summaries at the Eurozine Review.

Why do I clutter up the internet with this stuff at all? Mainly because I'm trying to get into the habit of displaying as much as possible of what I'm doing in public. Also, Blogger is a decent interface for a notebook

Monday, May 16, 2011

mode function in python

Oddly, there seems to be no mode function in the python standard library. It feels like something that should have an optimized C version squirreled away somewhere. 'Mode' is too ambiguous to be easily searchable, alas. Anyway, here's a version that should be reasonably fast


from collections import defaultdict
def mode(iterable):
counts = defaultdict(int)
for item in iterable:
counts[item] += 1
return max(counts, key = counts.get)


Should be reasonably fast (for pure-python), though could eat up a lot of memory on an iterable contaning large items.

No comments:

Post a Comment