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)
  • return ans in sorted order

Let us see the following implementation to get better understanding −

Example 

Live Demo

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]

Updated on: 02-Dec-2020

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements