Suppose I have an array
arr = [1,2,2,3,4,5]
What would be the most efficient and "pythonic" way to find the item with the most occurrences and how many times it occurs in the list?
What would be the most efficient and "pythonic" way to find the item with the most occurrences and how many times it occurs in the list?
Use Collections.Counter to get a dict
of each element with value as their occurrence and use most_common for finding the element having highest occurence. Try this:
import collections
arr = [1,2,3,4,5,3]
counts = collections.Counter(arr)
print("Counter:", counts)
# counts.most_common() # Returns all unique items and their counts
print("Most Occurred:", counts.most_common(1)[0][0]) # Returns the highest occurring item
Outpus:
Counter: Counter({3: 2, 1: 1, 2: 1, 4: 1, 5: 1})
Most Occurred: 3