I am working on a python algorithm to find the most frequent element in the list.
def GetFrequency(a, element):
return sum([1 for x in a if x == element])def GetMajorityElement(a):n = len(a)if n == 1:return a[0]k = n // 2elemlsub = GetMajorityElement(a[:k])elemrsub = GetMajorityElement(a[k:])if elemlsub == elemrsub:return elemlsublcount = GetFrequency(a, elemlsub)rcount = GetFrequency(a, elemrsub)if lcount > k:return elemlsubelif rcount > k:return elemrsubelse:return None
I tried some test cases. Some of them are passed, but some of them fails.
For example, [1,2,1,3,4] this should return 1, buit I get None.
The implementation follows the pseudocode here: http://users.eecs.northwestern.edu/~dda902/336/hw4-sol.pdf The pseudocode finds the majority item and needs to be at least half. I only want to find the majority item.
Can I get some help? Thanks!