-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206project1.py
executable file
·179 lines (148 loc) · 5.3 KB
/
206project1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import os
import filecmp
import datetime
def getData(filename):
#Input: file name
#Ouput: return a list of dictionary objects where
#the keys will come from the first row in the data.
#Note: The column headings will not change from the
#test cases below, but the the data itself will
#change (contents and size) in the different test
#cases.
myFile = open(filename, 'r')
keys = myFile.readline().strip().split(",")
theDataList = []
for element in myFile.readlines():
dataDict = {}
dataList = element.strip().split(",")
index = 0
for key in keys:
dataDict[key] = dataList[index]
index += 1
theDataList.append(dataDict)
return theDataList
#Sort based on key/column
def mySort(data,col):
#Input: list of dictionaries
#Output: Return a string of the form firstName lastName
sortedList = sorted(data, key = lambda k: k[col])
return sortedList[0]['First'] + " " + sortedList[0]['Last']
#Create a histogram
def classSizes(data):
# Input: list of dictionaries
# Output: Return a list of tuples ordered by
# ClassName and Class size, e.g
# [('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)]
snrCount = 0
jnrCount = 0
sophCount = 0
freshCount = 0
countlist = []
for element in data:
if element['Class'] == 'Senior':
snrCount += 1
elif element['Class'] == 'Junior':
jnrCount += 1
elif element['Class'] == 'Sophomore':
sophCount += 1
elif element['Class'] == 'Freshman':
freshCount += 1
countlist.append(("Senior", snrCount))
countlist.append(("Junior", jnrCount))
countlist.append(("Sophomore", sophCount))
countlist.append(("Freshman", freshCount))
return sorted(countlist, reverse = True, key = lambda k: k[1])
# Find the most common day of the year to be born
def findDay(a):
# Input: list of dictionaries
# Output: Return the day of month (1-31) that is the
# most often seen in the DOB
DOBdict = {}
for element in a:
dayOfMonth = element['DOB'].split('/')[1]
if dayOfMonth not in DOBdict.keys():
DOBdict[dayOfMonth] = 1
else:
DOBdict[dayOfMonth] += 1
return int(sorted(DOBdict, reverse = True, key = DOBdict.get)[0])
# Find the average age (rounded) of the Students
def findAge(a):
# Input: list of dictionaries
# Output: Return the average age of students rounded
# to nearest integer
ageList = []
current_day = int(datetime.date.today().day)
current_month = int(datetime.date.today().month)
current_year = int(datetime.date.today().year)
# second person down
for person in a[1:]:
birthday, birthmonth, birthyear = person['DOB'].split('/')
# if birthday already happened
if ((current_day > int(birthday)) and (current_month > int(birthmonth))):
ageList.append(current_year - int(birthyear))
# if birthday hasn't happened
else:
ageList.append(current_year - int(birthyear) + 1)
return int(sum(ageList) / len(ageList))
#Similar to mySort, but instead of returning single
#Student, all of the sorted data is saved to a csv file.
def mySortPrint(a,col,fileName):
#Input: list of dictionaries, key to sort by and output file name
#Output: None
csv = open(fileName, 'w')
sortedList = sorted(a, key = lambda k: k[col])
for element in sortedList:
temp = []
for value in element.values():
temp.append(value)
row = ",".join(temp[:3])
csv.write(row + "\n")
csv.close()
return None
################################################################
## DO NOT MODIFY ANY CODE BELOW THIS
################################################################
## We have provided simple test() function used in main() to print what each function returns vs. what it's supposed to return.
def test(got, expected, pts):
score = 0;
if got == expected:
score = pts
print(" OK ",end=" ")
else:
print (" XX ", end=" ")
print("Got: ",got, "Expected: ",expected)
return score
# Provided main() calls the above functions with interesting inputs, using test() to check if each result is correct or not.
def main():
total = 0
print("Read in Test data and store as a list of dictionaries")
data = getData('P1DataA.csv')
data2 = getData('P1DataB.csv')
total += test(type(data),type([]),40)
print()
print("First student sorted by First name:")
total += test(mySort(data,'First'),'Abbot Le',15)
total += test(mySort(data2,'First'),'Adam Rocha',15)
print("First student sorted by Last name:")
total += test(mySort(data,'Last'),'Elijah Adams',15)
total += test(mySort(data2,'Last'),'Elijah Adams',15)
print("First student sorted by Email:")
total += test(mySort(data,'Email'),'Hope Craft',15)
total += test(mySort(data2,'Email'),'Orli Humphrey',15)
print("\nEach grade ordered by size:")
total += test(classSizes(data),[('Junior', 28), ('Senior', 27), ('Freshman', 23), ('Sophomore', 22)],10)
total += test(classSizes(data2),[('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)],10)
print("\nThe most common day of the year to be born is:")
total += test(findDay(data),13,10)
total += test(findDay(data2),26,10)
print("\nThe average age is:")
total += test(findAge(data),39,10)
total += test(findAge(data2),41,10)
print("\nSuccessful sort and print to file:")
mySortPrint(data,'Last','results.csv')
if os.path.exists('results.csv'):
total += test(filecmp.cmp('outfile.csv', 'results.csv'),True,10)
print("Your final score is: ",total)
# Standard boilerplate to call the main() function that tests all your code.
if __name__ == '__main__':
main()