def mode(list):
modelist = max([list.count(x) for x in list])
return [i for i in list if list.count(i) == modelist][0]
Essentially, the code above works in most cases. However, I want the code to favor the lesser value when there are two equal values. so if the input list was [5,2,2,5] I want it to print 2 instead of printing 5
CodePudding user response:
Is there a reason you don't want to use multimode from the statistics library?
from statistics import multimode
print (min(multimode([2,5,2,5,3,3])))
CodePudding user response:
You can return the min
of the list you already have:
def mode(lst):
modelist = max(lst.count(x) for x in lst)
return min(i for i in lst if lst.count(i) == modelist)
print(mode([5, 2, 2, 5])) # 2
The code as is now has quite a large time complexity; I guess it is O(n^2). To reduce it, you can set up a counter (e.g., by using collections.Counter
):
from collections import Counter
def mode(lst):
return min(x[1] for x in Counter(lst).most_common(1))
With a long list like [5, 2, 2, 5] * 5000
, time spent is like 7.429 vs 0.002 seconds (on my machine).