FCC | Mean-Variance-Standard Deviation Calculator
A solution for FreeCodeCamp Data Analysis with Python Mean-Variance-Standard Deviation Calculator challenge.
Problem
Create a function named calculate() in mean_var_std.py
that uses Numpy to output the mean, variance, standard deviation, max, min, and sum of the rows, columns, and elements in a 3 x 3 matrix.
The input of the function should be a list containing 9 digits. The function should convert the list into a 3 x 3 Numpy array, and then return a dictionary containing the mean, variance, standard deviation, max, min, and sum along both axes and for the flattened matrix.
The returned dictionary should follow this format:
{
'mean': [axis1, axis2, flattened],
'variance': [axis1, axis2, flattened],
'standard deviation': [axis1, axis2, flattened],
'max': [axis1, axis2, flattened],
'min': [axis1, axis2, flattened],
'sum': [axis1, axis2, flattened]}
If a list containing less than 9 elements is passed into the function, it should raise a ValueError
exception with the message: “List must contain nine numbers.” The values in the returned dictionary should be lists and not Numpy arrays.
Notes
In NumPy
:
- Mean:
numpy.mean
- Variance:
numpy.var
- Standard deviation:
numpy.std
- Max:
numpy.max
- Min:
numpy.min
Steps
if
number of elements in the list is not equal to 9, then raise
a ValueError
with message.
if len(input_list) != 9:
raise ValueError("List must contain nine numbers.")
Convert the input list to a numpy
3x3 array.
numpy_array = np.array(input_list).reshape((3.3))
Calculate and return the result.
import numpy as np
def calculate(list):
if len(list) != 9:
raise ValueError("List must contain nine numbers.")
num_array = np.array(list).reshape((3,3))
calculations = {
'mean': [num_array.mean(axis=0).tolist(),
num_array.mean(axis=1).tolist(),
num_array.mean()],
'variance': [
num_array.var(axis=0).tolist(),
num_array.var(axis=1).tolist(),
num_array.var()
],
'standard deviation': [
num_array.std(axis=0).tolist(),
num_array.std(axis=1).tolist(),
num_array.std()
],
'max': [
num_array.max(axis=0).tolist(),
num_array.max(axis=1).tolist(),
num_array.max()],
'min': [
num_array.min(axis=0).tolist(),
num_array.min(axis=1).tolist(),
num_array.min()],
'sum': [
num_array.sum(axis=0).tolist(),
num_array.sum(axis=1).tolist(),
num_array.sum()],
}
return calculations