There is a coding problem on CodingBat.com (Logic-2 Python section) that asks for a function to determine how many small chocolate bars are used for a weight requirement. The question is as follows:
We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.
make_chocolate(4, 1, 9) → 4make_chocolate(4, 1, 10) → -1make_chocolate(4, 1, 7) → 2
I came up with this solution to the problem but it still fails in "other tests". Is there any problem that causes this?
Code:
def make_chocolate(small, big, goal): if (small + 5*big < goal) or (goal % 5 > small): return -1 elif small >= goal: return small else: smallnum = 0 for i in range(1,big+1): if 5*i + small >= goal: if 5*i > goal: break smallnum = goal - 5*i return smallnumEDIT:I have managed to finish the problem thanks to Mariah Akinbi. I have updated the code as follows:
def make_chocolate(small, big, goal): if (small + 5*big < goal) or (goal % 5 > small): return -1 elif 5 <= goal: smallnum = 0 for i in range(1,big+1): if 5*i + small >= goal: if 5*i > goal: break smallnum = goal - 5*i return smallnum return goal