Mercurial Hosting > traffic-intelligence
changeset 1034:4069d8545922
updated mostCommong function
author | Nicolas Saunier <nicolas.saunier@polymtl.ca> |
---|---|
date | Wed, 20 Jun 2018 12:04:22 -0400 |
parents | 8ffb3ae9f3d2 |
children | 933588568bec |
files | trafficintelligence/tests/utils.txt trafficintelligence/utils.py |
diffstat | 2 files changed, 9 insertions(+), 23 deletions(-) [+] |
line wrap: on
line diff
--- a/trafficintelligence/tests/utils.txt Wed Jun 20 00:07:03 2018 -0400 +++ b/trafficintelligence/tests/utils.txt Wed Jun 20 12:04:22 2018 -0400 @@ -55,8 +55,8 @@ 'b' >>> mostCommon(list(range(10))+[1]) 1 ->>> mostCommon([list(range(2)), list(range(4)), list(range(2))]) -[0, 1] +>>> mostCommon([(1,2), (2,3), (1,2)]) +(1, 2) >>> res = sortByLength([list(range(3)), list(range(4)), list(range(1))]) >>> [len(r) for r in res]
--- a/trafficintelligence/utils.py Wed Jun 20 00:07:03 2018 -0400 +++ b/trafficintelligence/utils.py Wed Jun 20 12:04:22 2018 -0400 @@ -6,6 +6,7 @@ from pathlib import Path from math import sqrt, ceil, floor from copy import deepcopy, copy +from collections import Counter from scipy.stats import rv_continuous, kruskal, shapiro, lognorm, norm, t from scipy.spatial import distance @@ -747,29 +748,14 @@ # iterable section ######################### -def mostCommon(L): +def mostCommon(l): '''Returns the most frequent element in a iterable + The element must be hashable - taken from http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list''' - from itertools import groupby - from operator import itemgetter - # get an iterable of (item, iterable) pairs - SL = sorted((x, i) for i, x in enumerate(L)) - # print 'SL:', SL - groups = groupby(SL, key=itemgetter(0)) - # auxiliary function to get "quality" for an item - def _auxfun(g): - item, iterable = g - count = 0 - min_index = len(L) - for _, where in iterable: - count += 1 - min_index = min(min_index, where) - # print 'item %r, count %r, minind %r' % (item, count, min_index) - return count, -min_index - # pick the highest-count/earliest item - return max(groups, key=_auxfun)[0] - + new version from https://stackoverflow.com/questions/41612368/find-most-common-element + previous version from from http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list''' + return Counter(l).most_common(1)[0][0] + ######################### # sequence section #########################