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

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

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

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 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

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

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