Files
30-seconds-of-code/snippets/weighted_average.md
Isabelle Viktoria Maciohsek 7bf106316a Update weighted_average.md
2020-10-09 09:12:38 +03:00

472 B

title, tags
title tags
weighted_average math,list,intermediate

Returns the weighted average of two or more noumbers.

  • 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