我正在尝试在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。请帮助我确定为什么我的代码无法通过隐藏测试。感谢。
答案 0 :(得分:1)
我试图运行你的代码并且它有效。也许您可以尝试使用foreach($result['item'] as $item){
echo $item['CallRef']
}
将浮动数字舍入为任何小数,如下所示:
round