with open("grades.txt") as f:
data = f.read()
print(data)
records = data.split('\n')
print(records)
Jones:CSC 1301:4:A Jones:CSC 1302:4:A Jones:CSC 2720:3:B Smith:CSC 1301:4:B Smith:CSC 1302:4:B Smith:CSC 2720:3:A Blake:CSC 1301:4:B Blake:CSC 1301:4:B Blake:CSC 1301:4:B Blake:CSC 1301:4:B ['Jones:CSC 1301:4:A', 'Jones:CSC 1302:4:A', 'Jones:CSC 2720:3:B', 'Smith:CSC 1301:4:B', 'Smith:CSC 1302:4:B', 'Smith:CSC 2720:3:A', 'Blake:CSC 1301:4:B', 'Blake:CSC 1301:4:B', 'Blake:CSC 1301:4:B', 'Blake:CSC 1301:4:B']
grades = {}
for record in records:
r = record.split(':')
#print(r)
name = r[0]
cno = r[1]
credits = int(r[2])
grade = r[3]
if name not in grades:
grades[name] = [(cno,credits,grade)]
else:
#grades[name].append((cno,credits,grade))
grades[name] = grades[name] + [(cno,credits,grade)]
print(grades)
{'Jones': [('CSC 1301', 4, 'A'), ('CSC 1302', 4, 'A'), ('CSC 2720', 3, 'B')], 'Smith': [('CSC 1301', 4, 'B'), ('CSC 1302', 4, 'B'), ('CSC 2720', 3, 'A')], 'Blake': [('CSC 1301', 4, 'B'), ('CSC 1301', 4, 'B'), ('CSC 1301', 4, 'B'), ('CSC 1301', 4, 'B')]}
def gpa(name,grades):
numeric_grades = {'A':4, 'B':3, 'C':2, 'D':1, 'F':0}
if name in grades:
courses = grades[name]
result = 0.0
ncredits = 0
for course in courses:
crs = course[1]
grade = numeric_grades[course[2]]
ncredits = ncredits + course[1]
result = result + grade*crs
return result/ncredits
else:
return None
print(gpa('Jones',grades))
3.727272727272727
print(gpa('Smith',grades))
3.272727272727273
print(gpa('Blake',grades))
3.0
print(gpa('Sunderraman',grades))
None