74.3k views
3 votes
As of Spring 2020, in otder to get into the CS major, you must have a 3.0 GPA or better in cs120, cs210, and cs245. In this problem, you should write one function named get_gpa, which will calculate this GPA. This function should have one parameter, which will be a dictionary of grades in computer science courses. You can assume that the dictionary will always have the keys 'cs120', 'cs210', and 'cs245', but it also might contain some names of other courses too. The values associated with each key will be a float representeing the GPA-style grade for that class. For instance, the parameter dictionary might look like: {'cs120':4.0 'cs245':3.0, 'cs210':2.0}. Some examples:

get_gpa({'cs110': 4.0, 'cs245':3.0, 'cs335':4.0, 'cs120':3.0, 'cs210':3.0}) should return 3.0.
get_gpa({'cs110': 4.0, 'cs120':3.0, 'cs245':2.0, 'cs210':1.0}) should return 2.0.
get_gpa({'cs245':4.0, 'cs120':3.0, 'cs245':2.0}) should return 3.0.

Make sure to include only the one function in your file.

User Danish
by
6.4k points

1 Answer

2 votes

Answer:

The function is as follows:

def get_gpa(mydict):

gpa = 0

kount = 0

for course_code, gp in mydict.items():

if course_code == 'cs120' or course_code == 'cs210' or course_code == 'cs245':

gpa += float(gp)

kount+=1

return (gpa/kount)

Step-by-step explanation:

This defines the function

def get_gpa(mydict):

This initializes gpa to 0

gpa = 0

This initializes kount to 0

kount = 0

This iterates through the courses

for course_code, gp in mydict.items():

If course code is cs120 or cs210 or cs245

if course_code == 'cs120' or course_code == 'cs210' or course_code == 'cs245':

The gpa is added

gpa += float(gp)

And the number of courses is increased by 1

kount+=1

This returns the gpa

return (gpa/kount)

User Vassilis
by
6.0k points