Reputation: 81
Hi Community! Could You please help me regarding following issue? I do not manage do achieve an efficient solution for my problem. Any help is highly appreciated! Thanks to all of You in advance!
My Problem: As first step, I would like to identify the most frequent value(s) of a given list of integers. As second step, if there are multiple most frequent values, I would like to take the lowest among them.
Example: Given following list, I would like to receive the "5", as it is the lowest, most frequent value.
list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
Could You please help me? Thanks!
Upvotes: 0
Views: 1669
Reputation: 23770
It is possible to get the most common value out of multiple candidates in linear time using the built-in Counter
class:
from collections import Counter
l = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
counter = Counter(l)
_, top_freq = counter.most_common(1)[0]
lower_most_common = min(key for key, freq in counter.items() if freq == top_freq)
Upvotes: 2
Reputation: 17368
In [24]: list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
...:
In [25]: max(sorted(set(list)), key=list.count)
Out[25]: 5
Upvotes: 2