Can't find the problem with my code for "Halloween Candy" in the Code Coach
I wrote the following code for the problem. It seems to give correct output when I test it, but some hidden cases of the problem turn out to give wrong output with my code. What's wrong with it? X﹏X https://code.sololearn.com/cozDvA30VvPN/?ref=app
11/29/2020 2:57:40 PMBehrad Mokhtari
12 AnswersNew Answer
U can either use the Math.ceil() like : import math houses = int(input()) print(houses) p=math.ceil((2/houses)*100) print(p) or try this without ceil(): houses = int(input()) dolchance = 2 / houses percent = (dolchance * 100) + .5 print(round(percent))
End value shloud be rounded up. So adding 0.5 will give you wrong result.. If persent=0.4 => 0.4+0.5=0.9 => int result 1. But what if present =0.7 =>0.7+0.5=1.2=> int of result give you 2 but needed answer is 1. Behrad Mokhtari Use ceil function instead..
Personally on that one I had to use Math.ceil() to get ceiling division and round everything up
Behrad Mokhtari In your reply you said int makes 1.2 -> 1 and 1.9 -> 1. Yes. But am not saying about int. It's about 1.2 and 1.9 of your result persent., which is result of adding 0.5 to actual result persent. Actual persent is 0.7 and 1.4, ie (1.2-0.5, 1.9-0.5). Actually you have to apply ceil on these values and needed result is 1 and 2 but with your approach you getting 1 and 1. Hope you understand it now what I meant..
Use below code... houses = int(input()) from math import ceil if houses >= 3: x = (2/houses)*100 print(ceil(x))
Thank you all. I tried all of your suggestions and they worked. both ceil() and round() methods worked perfectly fine. yings, Alphin K Sajan, Roderick Davis. Jayakrishna🇮🇳 , the int() function rounds to the nearest whole number before the float value, meaning it simply deletes the digits after the '.' (1.2 -> 1 and also 1.9 -> 1). So I thought if you add 0.5 to the float and then use the int() function, it will round to the nearest number to the float, just like the rounding method we've learned in math. Have any of you guys tried my code? I tested it with 20 or more examples and it always gave me the correct answer. I still don't know why did the code coach rejected it :-)
Behrad Mokhtari you're welcome...
As a beginner,I wrote this: #houses = int(input()) #chance= 200//houses #if 200 % houses > 0: # print (int(chance)+1) #else : # print (int(chance)) For a non-English speaker,this "round UP"may be a little confusing,which make the problem really hard
If the percent decimal is between .0 and .5,your code will be rejected by the code coach
So if percent = int (percent + houses / (houses + 1)) It may work.You can try
Jayakrishna🇮🇳 I understand now. I didn't notice the problem says "round UP to the nearest whole number". I was rounding (not up) to the nearest whole number so my code would round 0.4 to 0 and 0.7 to 1 though both of them should be rounded up to 1. I was so dumb lmao. Thanks!
yings Your code works as well. Thanks!