Python Counter | Majority Element
Last Updated :
24 May, 2022
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).
Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows:
Examples:
Input : 3 3 4 2 4 4 2 4 4
Output : 4
Input : 3 3 4 2 4 4 2 4
Output : NONE
We have existing solution for this problem please refer Majority Element link. We can solve this problem quickly in Python using Counter(iterable) function. Approach is simple,
- Convert given list of elements into dictionary using Counter() method, having elements as keys and their frequencies as value.
- Now traverse complete dictionary and check for element whose frequency follows the condition greater than (n/2) where n is size of list. That element will be majority element.
from collections import Counter
def majority(arr):
freqDict = Counter(arr)
size = len (arr)
for (key,val) in freqDict.items():
if (val > (size / 2 )):
print (key)
return
print ( 'None' )
if __name__ = = "__main__" :
arr = [ 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 ]
majority(arr)
|
Output:
4
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...