Python Question:
Create a program that prints the majority vote in a list. A majority vote is an element that occurs > N/2 times in a list (where N is the length of the list).
Examples ["A", "A", "B"] ➞ "A"
["A", "A", "A", "B", "C", "A"] ➞ "A"
["A", "B", "B", "A", "C", "C"] ➞ None
We can make a hashmap and keep the frequency of all the elements.
Then we can traverse the hashmap to find which element has frequency more than N/2.
# Python program for finding out majority
# element in an array
def findMajority(arr, size):
m = {}
for i in range(size):
if arr[i] in m:
m[arr[i]] += 1
else:
m[arr[i]] = 1
count = 0
for key in m:
if m[key] > size / 2:
count = 1
print("Majority found :-",key)
break
if(count == 0):
print("No Majority element")
# Driver code
arr = [2, 2, 2, 2, 5, 5, 2, 3, 3]
n = len(arr)
# Function calling
findMajority(arr, n)
Please change the input in arr as required or you can make a for loop to provide user input capability.
please upvote if you find the answer helpful.
Get Answers For Free
Most questions answered within 1 hours.