Skip to content

Instantly share code, notes, and snippets.

@h8rry
Created June 8, 2015 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h8rry/4b81abc7130d80b5fd15 to your computer and use it in GitHub Desktop.
Save h8rry/4b81abc7130d80b5fd15 to your computer and use it in GitHub Desktop.
HK DS 6 Class 1 Homework
#!/usr/bin/python
# Import required libraries
import sys
from collections import defaultdict
# Start a counter and store the textfile in memory
impressionSum = 0.0
ageSum = 0.0
clickThruSum = 0.0
oldestAge = 0
ageDist = {}
ageDist = defaultdict(lambda: 0, ageDist)
lines = sys.stdin.readlines()
lines.pop(0)
# For each line, find the sum of index 2 in the list.
for line in lines:
currentAgeRecord = int(line.strip().split(',')[0])
impressionSum = impressionSum + int(line.strip().split(',')[2])
ageSum = ageSum + currentAgeRecord
clickThruSum = clickThruSum + int(line.strip().split(',')[3])
ageDist[currentAgeRecord] += 1
if currentAgeRecord > oldestAge:
oldestAge = currentAgeRecord
# Printing results
print 'Impression Sum: ', impressionSum
print 'Average Age: ', ageSum / len(lines)
print 'Average Click Per Impression: ', clickThruSum / impressionSum
print 'Oldest Age: ', oldestAge
print 'Age Distributions: ', ageDist
# Writing age distributions to a text file called ageDist.txt
f = open('ageDist.txt', 'w')
for key, value in ageDist.iteritems():
f.write("Age " + str(key) + ": " + str(value) + "\n")
f.close()
### EOF ###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment