Averages

The questions below are due on Sunday July 07, 2024; 10:00:00 PM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.

Link to relevant section of reading

In this problem, we will consider two different ways of averaging sets of numbers: the weighted mean and the geometric mean.

Part 1: Weighted Mean

The weighted mean of a list of n numbers a_1, a_2, \ldots, a_n with weights w_1, w_2, \ldots, w_n is the sum of the corresponding numbers and weights divided by the sum of weights:

\frac{\sum_{k=1}^n a_k \cdot w_k}{\sum_{k=1}^n w_k} = \frac{a_1 \cdot w_1+a_2 \cdot w_2+\ldots+a_n \cdot w_n}{w_1 + w_2 + \ldots + w_n}

Write a function weight_mean(numbers, weights) to compute the weighted mean of a list of numbers (which could be either ints or floats). One thing to watch out for is an empty list as input. It's not clear that any numeric answer makes sense here. You should return None in that case.

For example:

  • weight_mean([], []) should return None
  • weight_mean([5, 7], [1, 1]) should return 6.0
  • weight_mean([10, 2], [.5, 3.5]) should return 3.0

Notes:

  • While we won't grade this problem for style, it is good practice to document your function with a multi-line comment or docstring at the top, which we have done for you in previous weeks. A Python function docstring is a comment string, conventially encased in triple quotes, on the first line after the def statement of a function. The docstring describes the input(s) and output of the function. Someone reading your code should be able to figure out a function's behavior just by reading its docstring, without examining your code.
  • You may use Python's sum function, but no additional imports.

Submit your file for checking below:

  No file selected

Part 2: Geometric Mean

The geometric mean of a list of n numbers is the product of the numbers, raised to the power 1/n:

\left(\prod_{k=1}^n a_k\right)^{\frac{1}{n}} = \sqrt[n]{a_1a_2\ldots a_n}

Write a function geo_mean(numbers) to compute the geometric mean of a list of numbers (which could be either ints or floats). As in Part 1, your function should return None in the case of an empty input list.

For example: geo_mean([2, 8, 2, 8]) should return 4.0

Submit your file for checking below:

  No file selected

Next Exercise: Batching

Back to exercises