Voting problem using string operation – python

Here we will discuss about how do we write a program to find out which person voted for each radish preference using string operations

For that we have a text file which we need to save in our computer and give path to python.

You can download the input file from http://opentechschool.github.io/python-data-intro/files/radishsurvey.tx

After that run this code

for line in open(“radishsurvey.txt”):

line = line.strip()

parts = line.split(” – “)

name = parts[0]

vote = parts[1]

print(name + ” voted for ” + vote)

This will give formatted vote list for all names.

vote1a

Now if we want check who all have voted for “White Icicle” we need to execute below code

for line in open(“radishsurvey.txt”):

line = line.strip()

parts = line.split(” – “)

name, vote = parts

if vote == “White Icicle”:

print(name + ” likes White Icicle!”)

vote2a

We can count the votes also by below commands

vote3a

Now we may want to make generic function for the same

def count_votes(radish):

print(“Counting votes for ” + radish + “…”)

count = 0

for line in open(“radishsurvey.txt”):

line = line.strip()

name, vote = line.split(” – “)

if vote == radish:

count = count + 1

return count

print(count_votes(“White Icicle”))

print(count_votes(“Daikon”))

print(count_votes(“Sicily Giant”))

 

vote3

Counting votes for each radish variety is a bit time consuming, you have to know all the names in advance and you have to loop through the file multiple times. To escape this headache we will create a dictionary with which will contain names and their corresponding voting counts.

vote5

There can be some situation where same vote is present with different case or some spaces present

So now we can clean the data little bit before go for final result:

vote6aAnother case may be more than one vote by any voter, in that case we can cancel the vote for that voter. To check that we have executed below code

vote7a

After doing all the cleaning and fraud voter removal we can divide each task into a function which will make the code more readable

 

vote8a

Finally it is time to find out who is the winner of the vote this code will provide the names of winners even if there are more than one winner

winner_name = “No winner”

winner_votes = 0

winner_list = []

for name in counts:

if counts[name] >= winner_votes:

winner_votes = counts[name]

winner_name = name

winner_list.append(winner_name)

if len(winner_list) > 1:

print(“The winner are: ” + ‘,’.join(winner_list))

else:

print(“The winner is: ” + ‘,’.join(winner_list))

vote9

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Abdul Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Abdul
Guest

Clean and Well explained with screenshots. (y)