python 在字典中舍入浮点数

toe95027  于 2023-01-24  发布在  Python
关注(0)|答案(2)|浏览(113)

我在www.example.com上尝试了一个挑战codewars.com,但我不知道为什么我的代码无法通过测试用例。我应该在字典中将任何浮点数舍入到2个小数点。我做了一些研究,发现了Round off dict values to 2 decimalsPython - how to round down to 2 decimals。我还在本地PC上测试了代码,它通过了所有测试。但是,第三个测试用例是codewars.com的隐藏测试,因为codewars.com有两个用户可见的测试,但是代码必须通过三个测试。2我从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}

用户在www.example.com上可以看到的两个测试用例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中找到。请帮助我确定为什么我的代码无法通过隐藏测试。谢谢。

w8rqjzmb

w8rqjzmb1#

我试着运行你的代码,它工作。也许你可以尝试使用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
wpx232ag

wpx232ag2#

在这里,它的工作!非常感谢您的分享伴侣:)

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

相关问题