在字典中舍入浮点数

Rounding float numbers within a dictionary

我正在 codewars.com 尝试挑战,但我无法弄清楚为什么我的代码无法通过测试 cases.I 应该将字典中的任何浮点数四舍五入到小数点后两位.我做了一些研究,发现 Round off dict values to 2 decimals and 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。请帮助我确定为什么我的代码无法通过隐藏测试。谢谢。

我试过 运行 你的代码并且它有效。也许您可以尝试使用 round 将浮点数四舍五入为任意小数,如下所示:

def split_the_bill(x):
    keys = list(x.values())
    keys2 = list(x.keys())
    average = mean(keys)
    keys3 = [(round(i-average, 1)) for i in keys]
    ans = dict( zip( keys2, keys3))
    return ans