Using the following dictionary, create a program that takes an argument (subject) and prints the average score excluding that subject, to two decimals.
grades = {'Biology':80, 'Physics':88, 'Chemistry':98, 'Math':89, 'English':79, 'Music':67, 'History':68, 'Art':53, 'Economics':95, 'Psychology':88}
For example:
- If the argument is Biology, it should print 80.56
- If the argument is Chemistry, it should print 78.56
Below what I've tried so far:
import sys
grades = {'Biology':80, 'Physics':88, 'Chemistry':98, 'Math':89, 'English':79, 'Music':67, 'History':68, 'Art':53, 'Economics':95, 'Psychology':88}
def average_grade():
key = sys.argv[1]
included_keys = grades.pop(key)
average = sum(included_keys)/len(included_keys)
return round(average, 2)
average_grade()
CodePudding user response:
This will work. I just deleted the specific subject from the dictionary with a del
statement, then I get all the values with grades.values()
and I get the number of grades left with len(grades)
.
import sys
grades = {'Biology':80, 'Physics':88, 'Chemistry':98, 'Math':89, 'English':79, 'Music':67, 'History':68, 'Art':53, 'Economics':95, 'Psychology':88}
def average_grade():
key = sys.argv[1]
del grades[key]
average = sum(grades.values())/len(grades)
return round(average, 2)
print(average_grade())
py file.py Biology
it outputs80.56
py file.py Chemistry
it outputs78.56
Of course it would be best to use some sort of error checking as well.
For example:
def average_grade():
key = sys.argv[1]
if key not in grades:
return "Subject does not exist. Please try again."
del grades[key]
average = sum(grades.values())/len(grades)
return round(average, 2)
if __name__ == "__main__":
print(average_grade())
Now if I enter py file.py German
it outputs Subject does not exist. Please try again.
CodePudding user response:
I would suggest using a copy of the dictionary, so the original dictionary will remain the same.
grades = {'Biology':80, 'Physics':88, 'Chemistry':98, 'Math':89, 'English':79, 'Music':67, 'History':68, 'Art':53, 'Economics':95, 'Psychology':88}
def average_grade(key):
g = grades.copy()
try:
g.pop(key)
except KeyError:
print('Subject not exixts')
return None
average = sum(g)/len(g)
return round(average, 2)
print(average_grade())
In your code
included_keys = grades.pop(key)
will return a number not a list and the calculation goes wrong hereaverage = sum(included_keys)/len(included_keys)
CodePudding user response:
Use a generator expression to skip the unwanted key, and statistics.mean
to calculate the mean.
from statistics import mean
def average_grade(grades, exclude):
if exclude in grades:
return mean(v for k, v in grades.items()
if k != exclude)
raise KeyError(f'Subject "{exclude}" not found')
average = average_grade(grades, sys.argv[1])
print(f"{average:.2f}")