From 0c377fe398df3f7fc1119139c46fc9e4097df5fb Mon Sep 17 00:00:00 2001 From: casalazara Date: Thu, 8 Oct 2020 23:00:33 -0500 Subject: [PATCH 1/2] Create weighted_average.md --- snippets/weighted_average.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 snippets/weighted_average.md diff --git a/snippets/weighted_average.md b/snippets/weighted_average.md new file mode 100644 index 000000000..13267d6f7 --- /dev/null +++ b/snippets/weighted_average.md @@ -0,0 +1,18 @@ +--- +title: weighted_average +tags: list,intermediate +--- + +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 `for i in range(len(nums))` to move over every number in the two lists. + +```py +def weightedAverage(nums,weights): + return sum(nums[i] * weights[i] for i in range(len(nums))) / sum(weights) +``` + +```py +weightedAverage([1, 2, 3], [0.6,0.2,0.3]) # 1.727272727272727 +``` From 7bf106316a9409b0e6bbd499324e2e9a69d3425a Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Fri, 9 Oct 2020 09:12:38 +0300 Subject: [PATCH 2/2] Update weighted_average.md --- snippets/weighted_average.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/snippets/weighted_average.md b/snippets/weighted_average.md index 13267d6f7..91ace1ece 100644 --- a/snippets/weighted_average.md +++ b/snippets/weighted_average.md @@ -1,18 +1,18 @@ --- title: weighted_average -tags: list,intermediate +tags: math,list,intermediate --- 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 `for i in range(len(nums))` to move over every number in the two lists. +- 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. ```py -def weightedAverage(nums,weights): - return sum(nums[i] * weights[i] for i in range(len(nums))) / sum(weights) +def weighted_average(nums, weights): + return sum(x * y for x, y in zip(nums, weights)) / sum(weights) ``` ```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 ```