Data Analysis with Python - Mean-Variance-Standard Deviation Calculator

I’m not sure what the issue is here, I’m getting 2 errors on the test_module but the code looks pretty correct to me.

ERROR: test_calculate (test_module.UnitTests)

Traceback (most recent call last):
File “/Users/peteraugerinos/Desktop/明けの明星 /Coding/PyCerts/PyDataAn/problems/problem1/test_module.py”, line 10, in test_calculate
self.assertAlmostEqual(actual, expected, “Expected different output when calling ‘calculate()’ with ‘[2,6,2,8,4,0,1,5,7]’”)
File “/Library/Frameworks/Python.framework/Versions/3.10/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()

======================================================================
ERROR: test_calculate2 (test_module.UnitTests)

Traceback (most recent call last):
File “/Users/peteraugerinos/Desktop/明けの明星 /Coding/PyCerts/PyDataAn/problems/problem1/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 “/Library/Frameworks/Python.framework/Versions/3.10/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()

def calculate(list):
    if len(list) != 9:
        raise ValueError("List must contain nine numbers.")
    data = np.array(list)
    data = data.reshape((3,3))
    calculations = {}
    mean = [np.mean(data, axis=0).astype('float32'), np.mean(data, axis=1).astype('float32'), np.mean(data)]
    variance = [np.var(data, axis=0).astype('float32'), np.var(data, axis=1).astype('float32'), np.var(data)]
    standard_deviation = [np.std(data, axis=0).astype('float32'), np.std(data, axis=1).astype('float32'), np.std(data)]
    maximum = [np.max(data, axis=0), np.max(data, axis=1), np.max(data)]
    minimum = [np.min(data, axis=0), np.min(data, axis=1), np.min(data)]
    total = [np.sum(data, axis=0), np.sum(data, axis=1), np.sum(data)]
    calculations = {'mean' : mean,
            'variance' : variance,
            'standard_deviation' : standard_deviation,
            'maximum' : maximum,
            'minimum' : minimum,
            'total' : total}
    return calculations

The error is telling you that you’re producing an array for the test and it can’t handle one. You’re best course of action for debugging this is to add

print(actual)
print(expected)

right before the assertion in test_calculate and compare the outputs because not only are your types wrong, your keys are wrong, and you’re trying to strongly type numbers as float32 when there is no need to do so.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.