Saturday, March 31, 2012

Python: Get the most frequent elements from list when there is more than one

Reference: stackoverflow
Authors: james_kansas, Niklas B.

The question is: When you are given a list that is unsorted, how do you get the most frequent appeared element, in particular, when there is more than one.
from collections import Counter

def myFunction(myDict):
    myMax = 0 # Keep track of the max frequence
    myResult = [] # A list for return
    for key in myDict:
        # Finding out the max frequence
        if myDict[key] >= myMax:
            if myDict[key] == myMax:
                myMax = myDict[key]
                myResult.append(key)
            # Case when it is greater than, we will delete and append
            else:
                myMax = myDict[key]
                del myResult[:]
                myResult.append(key)
    return myResult

foo = ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
print('The list:', foo)
myCount = Counter(foo)
print(myCount)

print(myFunction(myCount))
Output
The list: ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
Counter({'1': 3, '2': 3, '10': 1, '5': 1, '7': 1, '6': 1})
['1', '2']

More Reading: http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list

No comments:

Post a Comment