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) → 4 make_chocolate(4, 1, 10) → -1 make_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 smallnum
EDIT: 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
Your code seems to fail on:
make_chocolate(8,1,7)
--> returns 8 instead of 2
I believe the issue is:
elif small >= goal:
return small
The instructions say to use the big bars first, then use the nuggets to meet the goal.
Эта статья взята из Интернета, укажите источник при перепечатке.
Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.
я говорю два предложения