Reputation: 67
My program below does find the most frequent element in a list:
numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0]
counter = []
for num in range(10):
n = numbers.count(num)
counter.append(n)
largest = max(counter)
print(counter.index(largest))
Output is 7 which is correct.
However, if I add another 9 to the list:
numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
which means there are two most frequent elements in a list (in this case, both 7 and 9 are found three times there, as shown above), it only prints one of them - 7 in this case.
Is there any way how to change my code, so that the output will be correct?
Upvotes: 3
Views: 3293
Reputation: 1
numbers = [1,4,4,4,8,8,9,0,4]
most_friquent = max(numbers,key=numbers.count)
print (most_friquent)
Upvotes: 0
Reputation: 24232
Here is a solution that works for any kind of data, not only for positive integers in a range known beforehand.
We count using a collections.Counter
, extract the maximum count which is the count of the most_common number, then make a list of the numbers who have the same count:
from collections import Counter
numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
counts = Counter(numbers)
max_count = counts.most_common(1)[0][1]
out = [value for value, count in counts.most_common() if count == max_count]
print(out)
# [7, 9]
Upvotes: 6
Reputation: 514
Here's my way:
numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
counter = set([x for x in numbers if numbers.count(x) > 1])
print(max(counter))
# 9
Upvotes: 0
Reputation: 867
As the indices of the list counter
reflect a sorted value list, a simple solution would be to take the highest index: len(counter) - 1 - counter[::-1].index(largest)
Upvotes: 0
Reputation: 10304
from itertools import groupby
numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
counts = [(i, len(list(c))) for i,c in groupby(numbers)]
print(counts)
Upvotes: 0