Open In App

Dictionary and counter in Python to find winner of election

Last Updated : 27 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name.

Examples: 

Input :  votes[] = {"john", "johnny", "jackie", 
                    "johnny", "john", "jackie", 
                    "jamie", "jamie", "john",
                    "johnny", "jamie", "johnny", 
                    "john"};
Output : John
We have four Candidates with name as 'John', 
'Johnny', 'jamie', 'jackie'. The candidates
John and Johny get maximum votes. Since John
is alphabetically smaller, we print it.

We have existing solution for this problem please refer Find winner of an election where votes are represented as candidate names link. We can solve this problem quickly in python using Dictionary data structure

Method 1: 

Approach is very simple, 

  1. Convert given list of votes into dictionary using Counter(iterator) method. We will have a dictionary having candidate names as Key and their frequency ( counts ) as Value.
  2. Since more than 1 candidate may get same number of votes and in this situation we need to print lexicographically smaller name, so now we will create another dictionary by traversing previously created dictionary, counts of votes will be Key and candidate names will be Value.
  3. Now find value of maximum vote casted for a candidate and get list of candidates mapped on that count value.
  4. Sort list of candidates having same number of maximum votes and print first element of sorted list in order to print lexicographically smaller name.

Implementation:

Python3




# Function to find winner of an election where votes
# are represented as candidate names
from collections import Counter
 
def winner(input):
 
    # convert list of candidates into dictionary
    # output will be likes candidates = {'A':2, 'B':4}
    votes = Counter(input)
     
    # create another dictionary and it's key will
    # be count of votes values will be name of
    # candidates
    dict = {}
 
    for value in votes.values():
 
        # initialize empty list to each key to
        # insert candidate names having same
        # number of votes
        dict[value] = []
 
    for (key,value) in votes.items():
        dict[value].append(key)
 
    # sort keys in descending order to get maximum
    # value of votes
    maxVote = sorted(dict.keys(),reverse=True)[0]
 
    # check if more than 1 candidates have same
    # number of votes. If yes, then sort the list
    # first and print first element
    if len(dict[maxVote])>1:
        print (sorted(dict[maxVote])[0])
    else:
        print (dict[maxVote][0])
 
# Driver program
if __name__ == "__main__":
    input =['john','johnny','jackie','johnny',
            'john','jackie','jamie','jamie',
            'john','johnny','jamie','johnny',
            'john']
    winner(input)


Output

john

Time complexity : O(nlogn) 
Auxiliary Space : O(n)

Method 2: 

This is a shorter method.

  1. Count the number of votes for each person and stores in a dictionary. 
  2. Find the maximum number of votes. 
  3. Find corresponding person(s) having votes equal to maximum votes. 
  4. As we want output according to lexicographical order, so sort the list and print first element. 

Implementation:

Python3




from collections import Counter
 
votes =['john','johnny','jackie','johnny','john','jackie',
    'jamie','jamie','john','johnny','jamie','johnny','john']
 
#Count the votes for persons and stores in the dictionary
vote_count=Counter(votes)
 
#Find the maximum number of votes
max_votes=max(vote_count.values())
 
#Search for people having maximum votes and store in a list
lst=[i for i in vote_count.keys() if vote_count[i]==max_votes]
 
#Sort the list and print lexicographical smallest name
print(sorted(lst)[0])


Output

john

Time complexity : O(n) 
Auxiliary Space : O(1)



Similar Reads

Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Find winner of an election where votes are represented as candidate names
Given an array of names of candidates in an election. A candidate's name in the array represents a vote cast on the candidate. Print the name of candidates who received the maximum vote. If there is a tie, print a lexicographically smaller name. Examples: Input: votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "j
10 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Find who won the election based on given voting system
Given an array of pairs arr[][] of the form {X, Y} such that each arr[i] represents the time X at which the candidate with candidate ID Y was voted and an array of queries query[] consisting of M positive integers, the task for each query Q[i] is to find the winning candidate ID at that time Q[i] of voting. Note: In case, there are 2 candidates wit
11 min read
Election algorithm and distributed processing
Distributed Algorithm is an algorithm that runs on a distributed system. Distributed system is a collection of independent computers that do not share their memory. Each processor has its own memory and they communicate via communication networks. Communication in networks is implemented in a process on one machine communicating with a process on a
10 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python Counter to find the size of largest subset of anagram words
Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan
5 min read
Python Counter| Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1) We have existi
2 min read
Find winner of game where simultaneous decrement and increment of two elements done in one move
Given an arr[] of positive integers of length N. Player X and Y plays a game where in each move one person chooses two elements of arr[] (say arr[i] and arr[j]) such that 0 ? i < j ? N - 1 and arri should be greater than 0 and Then decrement arri and increment arrj. When one player is unable to make such a move the player loses. The task is to f
7 min read
Article Tags :
Practice Tags :