Python numpy统计量计算函数单元测试失败求助
Fixing TypeError in NumPy Statistics Function for Unit Tests
Let's break down what's going wrong here and fix it step by step.
The Root Cause of the TypeError
Your calculate function is returning the result of multiple print() calls, and each print() returns None. So when you do return print(mean), print(variance), ..., you're actually returning a tuple of 6 None values. The unit tests expect a single dictionary containing all the statistics, so when assertAlmostEqual tries to subtract this tuple from the expected dict, it throws the TypeError you're seeing.
Modified Working Code
Here's the fixed version of your function that will pass all the tests:
import numpy as np def calculate(arr): if len(arr) != 9: raise ValueError('List must contain nine numbers.') arr = np.array(arr) new_arr = arr.reshape((3, 3)) # Build a single stats dictionary matching the test's expected structure stats = { 'mean': [np.mean(new_arr, 0).tolist(), np.mean(new_arr, 1).tolist(), np.mean(arr).tolist()], 'variance': [np.var(new_arr, 0).tolist(), np.var(new_arr, 1).tolist(), np.var(arr).tolist()], 'standard deviation': [np.std(new_arr, 0).tolist(), np.std(new_arr, 1).tolist(), np.std(arr).tolist()], 'max': [np.max(new_arr, 0).tolist(), np.max(new_arr, 1).tolist(), np.max(arr).tolist()], 'min': [np.min(new_arr, 0).tolist(), np.min(new_arr, 1).tolist(), np.min(arr).tolist()], 'sum': [np.sum(new_arr, 0).tolist(), np.sum(new_arr, 1).tolist(), np.sum(arr).tolist()] } # Optional: print for debugging, but don't return the print result print(stats) return stats # Test the function directly if needed calculate([0, 1, 2, 3, 4, 5, 6, 7, 8])
Key Changes Made
- Replaced separate small dictionaries with one unified
statsdictionary that exactly matches the structure the unit tests expect. - Returned the
statsdictionary instead of a tuple ofprint()results (sinceprint()always returnsNone). - Kept the print statement as an optional debugging tool without affecting the function's return value.
Recommended Learning Resources
- NumPy Statistics: Master axis-based calculations and core stats functions with NumPy's official Statistics Routines documentation.
- Python Function Returns: Brush up on return value basics—remember
print()doesn't return the value it displays, it returnsNone. This is covered in Python's Function Definitions tutorial. - Unit Testing: Learn how
assertAlmostEqualworks (it compares numeric values or structures containing them) and other unittest methods via the official unittest documentation.
内容的提问来源于stack exchange,提问作者Doryk
相关产品推荐
相关产品推荐

