Change language

Dictionary and counter in Python to find the winner of an election

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 a solution to this problem, please refer to candidate names . We can quickly fix this problem in Python using Dictionary data structure . The approach is very simple,

  1. Convert the given list of votes to a dictionary using counter (iterator) . We will have a dictionary with the names of candidates as key and their frequency (number) as values ​​.
  2. Since more than one candidate can receive the same number of votes , and in this situation we need to print a lexicographically smaller name, so now we will create another dictionary, going through the previously created dictionary, the number of votes will be key, and the names of candidates —  value .
  3. Now find the value for the maximum number of votes cast for a candidate and get a list of candidates matched against that count.
  4. Sort the list of candidates who have the same number of votes, and print the first element of the sorted list to print a lexicographically smaller name.

# Function to find the winner of the election, where votes are
# presented as candidate names

from collections import Counter

  

def winner ( input ):

  

# convert candidate list to dictionary

# the output will look like candidates = {& # 39; A & # 39 ;: 2, & # 39; B & # 39 ;: 4}

votes = Counter ( input )

 

# create another dictionary and its key

# be the number of votes the value will be name

# candidates

dict = {}

 

for value in votes.values ​​():

 

# initialize empty list for each key

# insert candidate names that have the same

number of votes

  dict [value] = []

 

for (key, value) in votes.iteritems ():

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 candidate they have the same

# number of votes. If so, 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 

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically