我使用这些元素测试我的代码并得到4.6,但是当我尝试断言时,解释器返回一个断言错误。
def function(x):
a = 0
x.remove(min(x))
x.remove(max(x))
for i in x:
a = a + i
return float(1)/len(x)*a
assert function([3, 1, 2, 5, 9, 11, 4]) == 4.6
答案 0 :(得分:0)
对不起我还不能评论,但看起来@jonsharpe是对的。存在浮点精度问题。我输入了print abs(test - 4.6) < 0.001
并且返回了真实。我还导入了unittest并使用了assertEqual(我将发布以下代码:
import unittest
def function(x):
a = 0
x.remove(min(x))
x.remove(max(x))
for i in x:
a = a + i
return float(1)/len(x)*a
tc = unittest.TestCase('__init__')
tc.assertEqual(function([3, 1, 2, 5, 9, 11, 4]), 4.6)
从创建测试用例的实例并运行它,它显示了底层错误的更多内容。以下是我通过运行此结果得到的结果:
Traceback (most recent call last):
File "test.py", line 12, in <module>
tc.assertEqual(function([3, 1, 2, 5, 9, 11, 4]), 4.6)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 515, in assertEqual
assertion_func(first, second, msg=msg)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 508, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: 4.6000000000000005 != 4.6
我希望这可以帮助您找出问题并找到解决方案!