w3resource logo


Python Exercises

Python Challenges: Find majority element in a list

Python Challenges - 1: Exercise-29 with Solution

Write a Python program to find majority element in a list.

Input : [1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6]
Output : 5

Note: The majority element is the element that appears more than n/2 times where n is the number of elements in the list.

Explanation :

Python: Find majority element in a list

Sample Solution :-

Python Code :

def majority_element(num_list):
        idx, ctr = 0, 1
        
        for i in range(1, len(num_list)):
            if num_list[idx] == num_list[i]:
                ctr += 1
            else:
                ctr -= 1
                if ctr == 0:
                    idx = i
                    ctr = 1
        
        return num_list[idx]

print(majority_element([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6]))

print(majority_element([1,2,3,4,3,3,2,4,5,6,1,2,3,4,6,1,2,3,4,6,6]))

Output :

5                                                                       
6 

Flowchart:

Python Flowchart: Find majority element in a list

Python Code Editor:

def majority_element(num_list):
        idx, ctr = 0, 1
        
        for i in range(1, len(num_list)):
            if num_list[idx] == num_list[i]:
                ctr += 1
            else:
                ctr -= 1
                if ctr == 0:
                    idx = i
                    ctr = 1
        
        return num_list[idx]

print(majority_element([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6]))

print(majority_element([1,2,3,4,3,3,2,4,5,6,1,2,3,4,6,1,2,3,4,6,6]))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program