Update weighted_average.md
This commit is contained in:
committed by
GitHub
parent
0c377fe398
commit
7bf106316a
@ -1,18 +1,18 @@
|
|||||||
---
|
---
|
||||||
title: weighted_average
|
title: weighted_average
|
||||||
tags: list,intermediate
|
tags: math,list,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns the weighted average of two or more noumbers.
|
Returns the weighted average of two or more noumbers.
|
||||||
|
|
||||||
- Use `sum` to sum the products of the numbers by it's weight and to sum the weights.
|
- Use `sum()` to sum the products of the numbers by their weight and to sum the weights.
|
||||||
- Use `for i in range(len(nums))` to move over every number in the two lists.
|
- Use `zip()` and a list comprehension to iterate over the pairs of values and weights.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def weightedAverage(nums,weights):
|
def weighted_average(nums, weights):
|
||||||
return sum(nums[i] * weights[i] for i in range(len(nums))) / sum(weights)
|
return sum(x * y for x, y in zip(nums, weights)) / sum(weights)
|
||||||
```
|
```
|
||||||
|
|
||||||
```py
|
```py
|
||||||
weightedAverage([1, 2, 3], [0.6,0.2,0.3]) # 1.727272727272727
|
weighted_average([1, 2, 3], [0.6,0.2,0.3]) # 1.72727
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user