Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Weighted Average Coding

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Weighted Average Coding. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Cornerstone Learning Experience can combine scores from multiple assessments, where each assessment contributes according to its weight. Given parallel arrays of scores and weights, calculate the weighted average of all valid scores.

A score may be None, representing a missing assessment. Ignore that score and its weight. Ignore entries whose weight is zero. The input guarantees that at least one included score has a positive weight.

Formal Specification

Implement weighted_average(scores, weights):

  • scores is a list containing numbers or None.
  • weights is a list of nonnegative numbers with the same length as scores.
  • For every non-missing score with a positive weight, contribute score * weight to the numerator.
  • Return sum(score * weight) / sum(weight) as a floating-point number.
  • Do not round the result inside the function.

Constraints

  • 1 <= len(scores) == len(weights) <= 10^5
  • scores[i] is None or a number from 0 through 100
  • 0 <= weights[i] <= 10^6
  • At least one non-missing score has a positive weight
  • The two arrays have equal length

Function Signature

def weighted_average(scores, weights):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output