Posted by : Netbloggy Sunday, August 9, 2015

The best way to learn any programming language is to solve problems with it. While programming documentations can teach you syntax, you can get closer to the language only when you get hands-on with the code. So let's get started with our first problem in this python journey: Voting Problem

Problem:

We have 300 lines of survey data in the file radishsurvey.txt. Each line consists of a name, a hyphen, then a radish variety and so on. Our objective is to find answers for the following:


  • What's the most popular radish variety?
  • What are the least popular?
  • Did anyone vote twice?

Takeaways:

In our attempt to solve this problem, we'll come across the following concepts of python:
  • Reading & Cleaning a text file
  • Basic String Operations
  • Traversing a Dictionary & List
  • Iterative Looping and Conditional Looping 
  • Defining and Calling a function
Approach:

We can read the file radishsurvey.txt and put its contents in a file object to traverse it. Like this:


radish_contents = open("radishsurvey.txt")
for line in radish_contents:

 Instead we can directly use the file open() function in our iteration to reduce one step. But before that we are creating an empty dictionary counts to store the vote counts and an empty list voted to track the duplicate voters. Comments in the below code explain the purpose of every step.


counts = {}
voted = []
for line in open("radishsurvey.txt"):
    
    line1 = line.strip()
    #print line #remove this comment to see how the line would be printed without strip()
    name, vote = line1.split(" - ")
    vote = vote.strip().capitalize() #just to make the 'vote' elements in proper case

    vote = vote.replace("  "," ") #data cleaning: replacing two white spaces with one

    if name in voted:
        print name, "has already voted" #printing the voter's name who voted again                 continue  #skip their vote and process the next line
    voted.append(name) #for first time voters: adding their name to voted list

    if vote not in counts:
        # First vote for this variety - make a new entry in dictionary and set value to 1
        counts[vote] = 1
    else:
        # Increment the vote count as the entry is already present in the dictionary
        counts[vote] = counts[vote] + 1

We have successfully built a dictionary with Radish variety as Key and Vote count as its Value and also we've handled the most important test case of printing the duplicate voters and disregarding their vote.


for item in counts:
    print item, counts[item] 

While this code can give us all the details that we wanted, we still manually need to go through every line to see the most voted and least voted variety. And we, programmers who are meant to be lazy, would want the program itself to tell us that too.  Here's the code:


def find_winner(counts):
    winner = ""
    pre_vote = 0
    for vote in counts:
        if counts[vote] >= pre_vote:
            
            winner = vote
            pre_vote = counts[vote]
            
            
    return winner, pre_vote
    
def find_loser(counts):
    loser, pre_vote = find_winner(counts) #calling a function inside another fn.
    for vote in counts:
        if counts[vote] < pre_vote:
            
            loser = vote
            pre_vote = counts[vote]
            
    return loser, pre_vote

Here's the output after executing the code in python 2:

Phoebe Barwell has already voted
Procopio Zito has already voted
White icicle 64
Snow belle 63
Champion 76
Cherry belle 58
French breakfast 72
Daikon 63
Bunny tail 72
Sicily giant 57
Red king 56
Plum purple 56
April cross 72
And the winner is Mr. Champion with 76 votes
Sorry, the loser is Mr. Red king with 56 votes

Our objectives are met and hope you've learnt something from this blogpost.
Download the entire python code here.

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Popular Post

Blogger templates

Total Pageviews

Powered by Blogger.

- Copyright © nulldata -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -