Weighted Average From a List of Tuples

Medium ⏱ 12 min 61% acceptance ★★★★☆ 4.2
A student's grades are stored as a list of (score, credit_hours) tuples. Write weighted_average(grades) that returns the credit-hour-weighted average score, rounded to 2 decimal places. Assume the total credit hours is greater than 0.

Examples

Example 1
Input
grades = [(90, 3), (80, 4), (70, 2)]
Output
81.11
Explanation

(90*3 + 80*4 + 70*2) / (3+4+2) = 730/9 = 81.11 (rounded).

Constraints

  • 0 < sum of credit_hours
  • 1 <= len(grades) <= 10^4

Topics

ListsBusiness Logic

Companies

JPMorgan ChaseGoldman Sachs

Hints

Hint 1

Accumulate weighted_sum += score * hours and total_hours += hours in one pass, then divide.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.