1

Is there a way to output a list of the most occurring element from a list into a list or all of the most occurred elements if there is a tie?

I would like to solve this without importing any classes!

For example, [5,4,3] would output [5,4,3].

or

[5,4,4,5] would output [5,4]

I have tried, max(set(list), key=list.count) but does not really work for ties.

my work so far:

test = ['test1', 'test2', 'test3']
dict = {}

for elements in test:
    if elements in dict:
        dict[elements] += 1
    else:
        dict[elements] = 0
        dict[elements] += 1

print (dict)

1 Answers1

1

You could use collections.Counter, find the maximum count and then keep those that have maximum count:

from collections import Counter

counts = Counter([5, 4, 4, 5, 3])

max_count = max(counts.values())
result = [k for k, count in counts.items() if count == max_count]

print(result)

Output

[5, 4]

You could substitute the Counter by a simple dictionary:

data = [5, 4, 4, 5, 3]
counts = {}

for e in data:
    counts[e] = counts.get(e, 0) + 1

max_count = max(counts.values())
result = [k for k, count in counts.items() if count == max_count]

print(result)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76