Today we are going to share a Python Program for finding out majority element in an array. If you are a python beginner and want to start learning the python programming, then keep your close attention in this tutorial as I am going to share a Python Program for finding out majority element in an array.
To increase your Python knowledge, practice all Python programs, here is a collection of 100+ Python problems with solutions.
Copy the below python program and execute it with the help of python compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
def findCandidate(A): maj_index = 0 count = 1 for i in range(len(A)): if A[maj_index] == A[i]: count += 1 else: count -= 1 if count == 0: maj_index = i count = 1 return A[maj_index] # Function to check if the candidate occurs more than n/2 times def isMajority(A, cand): count = 0 for i in range(len(A)): if A[i] == cand: count += 1 if count > len(A)/2: return True else: return False # Function to print Majority Element def printMajority(A): # Find the candidate for Majority cand = findCandidate(A) # Print the candidate if it is Majority if isMajority(A, cand) == True: print(cand) else: print("No Majority Element") # Driver program to test above functions A = [1, 3, 3, 1, 2] printMajority(A) |
Majority found :- 2
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.