Mercurial Hosting > traffic-intelligence
comparison python/utils.py @ 455:abe0b2347d4c
added most common utility function
author | Nicolas Saunier <nicolas.saunier@polymtl.ca> |
---|---|
date | Tue, 18 Feb 2014 14:52:49 -0500 |
parents | 9a714f32fc9f |
children | 825e5d49325d |
comparison
equal
deleted
inserted
replaced
454:62d05436099d | 455:abe0b2347d4c |
---|---|
265 return result | 265 return result |
266 plot(x, y, 'x') | 266 plot(x, y, 'x') |
267 xx = arange(min(x), max(x),(max(x)-min(x))/1000) | 267 xx = arange(min(x), max(x),(max(x)-min(x))/1000) |
268 plot(xx, [poly(z) for z in xx]) | 268 plot(xx, [poly(z) for z in xx]) |
269 return coef | 269 return coef |
270 | |
271 ######################### | |
272 # iterable section | |
273 ######################### | |
274 | |
275 def mostCommon(L): | |
276 '''Returns the most frequent element in a iterable''' | |
277 from itertools import groupby | |
278 from operator import itemgetter | |
279 # get an iterable of (item, iterable) pairs | |
280 SL = sorted((x, i) for i, x in enumerate(L)) | |
281 # print 'SL:', SL | |
282 groups = groupby(SL, key=itemgetter(0)) | |
283 # auxiliary function to get "quality" for an item | |
284 def _auxfun(g): | |
285 item, iterable = g | |
286 count = 0 | |
287 min_index = len(L) | |
288 for _, where in iterable: | |
289 count += 1 | |
290 min_index = min(min_index, where) | |
291 # print 'item %r, count %r, minind %r' % (item, count, min_index) | |
292 return count, -min_index | |
293 # pick the highest-count/earliest item | |
294 return max(groups, key=_auxfun)[0] | |
270 | 295 |
271 ######################### | 296 ######################### |
272 # sequence section | 297 # sequence section |
273 ######################### | 298 ######################### |
274 | 299 |