이제 요구사항이 또 바뀐다. 각 점수의 가중치를 함께 저장해서 중간고사와 기말고사가 쪽지시험보다 성적에 더 중요하게 반영되도록 하고 싶다. 이런 기능을 구현하는 한 가지 방법은 가장 안쪽에 있는 딕셔너리가 과목(키)을 성적의 리스트(값)로 매핑하던 것 대신에 과목(키)을 (성적, 가중치) 튜플의 리스트로 매핑하도록 변경하는 것이다.
class WeightedGradebook:
def __init__(self):
self._grades = {}
def add_student(self, name):
self._grades[name] = defaultdict(list)
def report_grade(self, name, subject, score, weight):
by_subject = self._grades[name]
grade_list = by_subject[subject]
grade_list.append((score, weight)) # 변경함
def average_grade(self, name):
by_subject = self._grades[name]
score_sum, score_count = 0, 0
for scores in by_subject.values():
subject_avg, total_weight = 0, 0
for score, weight in scores:
subject_avg += score * weight
total_weight += weight
score_sum += subject_avg / total_weight
score_count += 1
return score_sum / score_count