Voting problem using string operation

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

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.


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!”)


We can count the votes also by below commands


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(“Sicily Giant”))


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.


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


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


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


if len(winner_list) > 1:

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


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


Leave a Comment

Scroll to Top