- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to list of candidates who have got majority vote in python
Suppose we have a list of numbers called nums where each number represents a vote to a candidate. We have to find the ids of the candidates that have greater than floor(n/3) votes, in non-decreasing order.
So, if the input is like nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7], then the output will be [6, 7], as 6 and 7 have 40% of the votes.
To solve this, we will follow these steps −
- ans := a new empty set
- sort the list nums
- i := 0
- n := size of nums
- while i < size of nums, do
- if occurrences of nums[i] in nums > (n / 3), then
- insert nums[i] into ans
- i := i + (n / 3)
- if occurrences of nums[i] in nums > (n / 3), then
- return ans in sorted order
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): ans = set([]) nums.sort() i = 0 n = len(nums) while i < len(nums): if nums.count(nums[i]) > n // 3: ans.add(nums[i]) i += n // 3 return sorted(list(ans)) ob = Solution() nums = [3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7] print(ob.solve(nums))
Input
[3, 2, 6, 6, 6, 6, 7, 7, 7, 7, 7]
Output
[6, 7]
Advertisements