0
我在Codewars.com上尝试了一个挑战,但我无法弄清楚为什么我的代码无法通过测试用例。我应该将任何浮点数舍入到字典中的2个小数点。我做了一些研究,发现Round off dict values to 2 decimals和Python - how to round down to 2 decimals。我还测试了本地PC上的代码,并通过了所有测试。但是,第三个测试用例是codewars.com上的隐藏测试,因为codewars.com有两个对用户可见的测试,但代码必须通过三个测试。我从codewars.com返回的消息中找出了第三个测试用例,如下所示。在字典中舍入浮点数字
Basic Tests
✔ Test Passed
✔ Test Passed
✘ {'A':-17.200000000000003,'C':-47.200000000000003,'B':-32.200000000000003,
'E': 0.79999999999999716, 'D': 95.799999999999997} should equal {'A': -17.2,
'C': -47.2, 'B': -32.2, 'E': 0.8, 'D': 95.8}
两个测试用例是对用户可见在codewars.com是
test.assert_equals(split_the_bill({'A': 20, 'B': 15, 'C': 10}), {'A': 5, 'B': 0, 'C': -5})
test.assert_equals(split_the_bill({'A': 40, 'B': 25, 'X': 10}), {'A': 15, 'B': 0, 'X': -15})
我的代码和我已用于测试相同的代码测试用例示于下面
from statistics import mean
import unittest
import math
############## My Code ####################################################
def split_the_bill(x):
keys = list(x.values())
keys2 = list(x.keys())
average = mean(keys)
keys3 = [(math.ceil((i-average)*100)/100) if type(i) == float else (i-average) for i in keys]
ans = dict(zip(keys2, keys3))
return ans
######################### My Test Case ###########################
class MyTestCases(unittest.TestCase):
def test(self):
new_string = split_the_bill({'A': 20, 'B': 15, 'C': 10})
self.assertEqual(new_string, {'A': 5, 'B': 0, 'C': -5},
msg = "should return {'A': 5, 'B': 0, 'C': -5}")
def test1(self):
new_string = split_the_bill({'A': 40, 'B': 25, 'X': 10})
self.assertEqual(new_string, {'A': 15, 'B': 0, 'X': -15},
msg = "should return {'A': 15, 'B': 0, 'X': -15}")
def test2(self):
new_string = split_the_bill({'A': -17.200000000000003, 'C': -47.200000000000003, 'B': -32.200000000000003, 'E': 0.79999999999999716, 'D': 95.799999999999997})
self.assertEqual(new_string, {'A': -17.2, 'C': -47.2, 'B': -32.2, 'E': 0.8, 'D': 95.8},
msg = "should return {'A': -17.2, 'C': -47.2, 'B': -32.2, 'E': 0.8, 'D': 95.8}")
if __name__ == "__main__":
unittest.main()
关于挑战的详尽说明可以在here找到。请帮助我确定为什么我的代码无法通过隐藏的测试。谢谢。