You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 stats dictionary that exactly matches the structure the unit tests expect.
  • Returned the stats dictionary instead of a tuple of print() results (since print() always returns None).
  • Kept the print statement as an optional debugging tool without affecting the function's return value.
  • 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 returns None. This is covered in Python's Function Definitions tutorial.
  • Unit Testing: Learn how assertAlmostEqual works (it compares numeric values or structures containing them) and other unittest methods via the official unittest documentation.

内容的提问来源于stack exchange,提问作者Doryk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:32:36