为什么这段代码在编码上给出错误'Timed Out'?



场景:我们想做一包"目标"公斤的巧克力。我们有小酒吧(每个1公斤(和大酒吧(每个5公斤(。返回要使用的小条数,假设我们总是在小条之前使用大条。如果无法完成,则返回-1。

是否存在某种情况导致它在无限循环中运行?

def make_chocolate(small, big, goal):
while goal >= 5 and big > 0:
goal -= 5
big -= 1
if small >= goal:
return goal
return -1

我建议您使用更多的算法来解决

def make_chocolate(small, big, goal):
big_that_can_fit = goal // 5
big_that_we_use = min(big_that_can_fit, big)
goal -= big_that_we_use * 5
if small >= goal:
return goal
return -1

过去了https://codingbat.com/prob/p190859测试

根据您的问题,我认为这个逻辑应该有效:

def make_chocolate(small, big, goal):
#Case when goal can't be made using the given quantity of chocolates (small or big)        
if (small + big *5 ) < goal:
return -1
#Case when the big bars will suffice, and the remaining goal may or may not require the smaller units
elif ((big * 5) > goal):
return goal % 5
#Number of small bars used otherwise
else:
return goal - big *5 

相关内容

最新更新