Sunday, 9 August 2015

Working with Strings,Tuples and Dictionary

As we all know python is one of the most used programming language in terms of developing. We will see how important it is in analytic perspective with the below program.

Case Study:

Suppose you're a greengrocer, and you run a survey to see what radish varieties your customers prefer the most. You have your assistant type up the survey results into a text file on your computer, so you have 300 lines of survey data each line consists of a name, a hyphen, and then a radish variety.


Objective:

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

Approach:

Step 1: First we will read the input file 'line-by-line' using 'for' and 'in' function.
       
                          for line in open("radishsurvey.txt"):

Step 2: Then we clean our data in 3 steps,
 
     Step 2.1 -  by stripping away all junks such as null characters in the EOL.

line1 = line.strip()

 Step 2.2 -  by splitting Customer Name with the Radish type voted.
 
                            name, vote = line1.split(" - ")

Step 2.3 -   by Capitalizing Radish types so that all entries follow same pattern of Radish Names.
 
                         vote = vote.strip().capitalize()

Step 3: Create a new list voted[],


Step 4: If the voter name is not existing in the list, add the name to "voted[]" list. Else print a warning saying "Customer has already voted"


Step 5: Create a dictionary counts{},


Step 6: Read the 'Radish Type' and assign it as key. Count the number of times the same Radish Type has been voted and assign it to Value.


if vote not in counts:
    counts[vote] = 1
else:
# Increment the vote count
    counts[vote] = counts[vote] + 1

Till Step 6 we created a program to get the unique voters, a table(dictionary) with Radish type and corresponding voted counts.


Step 7: Create a user defined function to get the maximum and minimum voted radish type.

Step 7.1: To calculate the most popular radish type,


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
pprint(counts)  
winner= find_winner(counts)
print "Most popular radish type is:",winner
 


Step 7.2: To calculate the least popular radish type,



def find_loser(counts):
 loser = ""
 loser,pre_vote = find_winner(counts)
 for vote in counts:
  if counts[vote] <= pre_vote:
   loser = vote
   pre_vote = counts[vote]
return loser, pre_vote
pprint(counts)  
loser= find_loser(counts)
print "Most non popular radish type is:",loser


Output:




Note - download the base used for this survey from the link - RadishType_DB

1 comment:

  1. Nicely written with highlighted syntax. Looking forward for more code :-)

    ReplyDelete