Files
30-seconds-of-code/snippets/weighted_average.md
Isabelle Viktoria Maciohsek 0f3e0f9ed0 Update snippet titles
2022-02-13 14:41:40 +02:00

549 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
Weighted average math,list,intermediate 2020-10-09T07:00:33+03:00 2020-12-24T15:00:53+02:00

Returns the weighted average of two or more numbers.

  • Use sum() to sum the products of the numbers by their weight and to sum the weights.
  • Use zip() and a list comprehension to iterate over the pairs of values and weights.
def weighted_average(nums, weights):
  return sum(x * y for x, y in zip(nums, weights)) / sum(weights)
weighted_average([1, 2, 3], [0.6, 0.2, 0.3]) # 1.72727