|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | + |
| 4 | +def weighted_average(values: list[float], weights: list[float]) -> float: |
| 5 | + """ |
| 6 | + Return the weighted average of a list of values given their corresponding weights. |
| 7 | +
|
| 8 | + https://en.wikipedia.org/wiki/Weighted_arithmetic_mean |
| 9 | +
|
| 10 | + >>> weighted_average([1, 2, 3], [1, 1, 1]) |
| 11 | + 2.0 |
| 12 | + >>> weighted_average([10, 20, 30], [1, 2, 3]) |
| 13 | + 23.333333333333332 |
| 14 | + >>> weighted_average([5, 15], [1, 3]) |
| 15 | + 12.5 |
| 16 | + >>> weighted_average([100], [0.5]) |
| 17 | + 100.0 |
| 18 | + >>> weighted_average([], []) |
| 19 | + Traceback (most recent call last): |
| 20 | + ... |
| 21 | + ValueError: Inputs cannot be empty |
| 22 | + >>> weighted_average([1, 2], [1]) |
| 23 | + Traceback (most recent call last): |
| 24 | + ... |
| 25 | + ValueError: Values and weights must have the same length |
| 26 | + >>> weighted_average([1, 2, 3], [0, 0, 0]) |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + ValueError: Sum of weights cannot be zero |
| 30 | + """ |
| 31 | + if not values and not weights: |
| 32 | + raise ValueError("Inputs cannot be empty") |
| 33 | + if len(values) != len(weights): |
| 34 | + raise ValueError("Values and weights must have the same length") |
| 35 | + total_weight = sum(weights) |
| 36 | + if total_weight == 0: |
| 37 | + raise ValueError("Sum of weights cannot be zero") |
| 38 | + return sum(value * weight for value, weight in zip(values, weights)) / total_weight |
| 39 | + |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + import doctest |
| 43 | + |
| 44 | + doctest.testmod() |
0 commit comments