Mean-Variance-Standard Deviation Calculator test_module error

Hi all

I am attempting the Boilerplate-mean-variance-standard-deviation-calculator found here: https://www.freecodecamp.org/learn/data-analysis-with-python/data-analysis-with-python-projects/mean-variance-standard-deviation-calculator and I am getting an error with the testing model with seems to be test_module.py use of the assertAlmostEqual function on a dictionary.

Here is my code:

import numpy as np

def calculate(list):

  #Check that list is a least 9 long
  if len(list)< 9:
    raise ValueError("List must contain nine numbers.")
  # Reshape list into 3*3 a=numpy array
  array = np.reshape(list[0:9], [3,3])
  print(array)
  calculations = {}
  calculations["mean"] = [array.mean(axis = 0, dtype = float), array.mean(axis = 1, dtype = float), array.mean( dtype = float)]
  calculations["variance"] = [array.var(axis = 0), array.var(axis = 1), array.var()]
  calculations['standard deviation'] = [array.std(axis = 0), array.std(axis = 1), array.std()]
  calculations['max'] = [array.max(axis = 0), array.max(axis = 1), array.max()]
  calculations['min'] = [array.min(axis = 0), array.min(axis = 1), array.min()] 
  calculations['sum'] = [array.sum(axis = 0), array.sum(axis = 1), array.sum()]
                          

  return calculations

and main.py looks like this:

import mean_var_std
from unittest import main

#print(mean_var_std.calculate([2,6,2,8,4,0,1,5,7]))
out = mean_var_std.calculate([2,6,2,8,4,0,1,5,7])
print(out['mean'][0])
# Run unit tests automatically
main(module='test_module', exit=False)

and my error is:

ERROR: test_calculate2 (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-mean-variance-standard-deviation-calculator/test_module.py", line 15, in test_calculate2
    self.assertAlmostEqual(actual, expected, "Expected different output when calling 'calculate()' with '[9,1,5,3,3,3,2,9,0]'")
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/unittest/case.py", line 870, in assertAlmostEqual
    if first == second:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


----------------------------------------------------------------------
Ran 3 tests in 0.004s

FAILED (errors=2)

Here is the link to my replit:

Any help is appreciated.

Solved this:
the testing module is expecting the outputs to be lists not numpy objects, so adding ’ .tolist()’ to each thing solves this eg:

calculations['max'] = [array.max(axis = 0).tolist(), array.max(axis = 1).tolist(), array.max().tolist()]

Does anyone know a neater way of doing this?

This looks neat to me.

You could also use:

list(array.max(axis = 0))

Great solution! Using .tolist() works well on a online calculator. Another option is to use list comprehensions for more concise code.