Your question is Optimizing Code Performance. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
Politecnico di Milano's exam office has a script that builds the per-course grade summary shown on the internal admin dashboard every night. The exam log has grown to hundreds of thousands of rows across thousands of courses, and the nightly job now takes long enough that it sometimes overlaps the next day's run.
def build_grade_report(exam_results, courses):
report = ""
for course in courses:
course_results = [r for r in exam_results if r["course_id"] == course["id"]]
sorted_results = sorted(exam_results, key=lambda r: r["grade"])
total = 0
count = 0
for r in course_results:
total += r["grade"]
count += 1
average = total / count if count > 0 else 0
report += f"{course['name']}: avg={average:.2f}, n={count}
"
return report
How would you optimize this piece of code for speed? Walk through what makes it slow at this scale and how you would fix each part.