I am trying out a challenge at codewars.com, but I cannot figure out why my code cannot pass the test cases.I am supposed to round of any float numbers to 2 decimal points within a dictionary. I have done some research and found Round off dict values to 2 decimals and Python - how to round down to 2 decimals. I have also tested the code on my local PC and it passes all the tests. However, the third test case is a hidden test at codewars.com because codewars.com has two tests visible to the user but the code must pass three tests. I figured out the third test case from the message returned from codewars.com which is shown below.
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}
The two test cases that are visible to the user at codewars.com are
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})
My code and testcases that I have used to test the same code are shown below
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()
Extensive instructions for the challenge can be found here. Kindly help me identify why my code cannot pass the hidden test. Thanks.
I tried to run your code and it works. Maybe you can try to use round
to round the floating number into any decimal as following:
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