Counter Python | Majority element

Counters | Python Methods and Functions

Write a function that takes an array and emits a majority element (if it exists), otherwise prints NONE like this:

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 a solution to this problem, please refer to the link Majority Element . We can quickly fix this problem in Python using the

# Function to find the majority element

from collections import Counter

 

def majority (arr):

 

# convert array to dictionary

  freqDict = Counter (arr)

  

# go through dictionary and check majority element

  size = len (arr)

for (key, val) in freqDict.items ():

if (val & gt; (size / 2 )):

print (key)

return

print ( 'None' )

 
# Driver program

if __ name__ = = "__ main__" :

arr = [ 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4

majority (arr)

Output:

 4 




Tutorials