Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么这段代码会给出错误';超时';关于编码蝙蝠?_Python_Loops - Fatal编程技术网

Python 为什么这段代码会给出错误';超时';关于编码蝙蝠?

Python 为什么这段代码会给出错误';超时';关于编码蝙蝠?,python,loops,Python,Loops,场景:我们想制作一包“目标”公斤巧克力。我们有小条(每个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公斤)和大条(每个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_巧克力(小、大、目标):
能适应的大目标=目标//5
我们使用的大尺寸=最小值(大尺寸适合,大尺寸)
目标-=我们使用的大目标*5
如果小>=目标:
返回目标
返回-1

通过测试

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

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 
def make_巧克力(小、大、目标):
#如果无法使用给定数量的巧克力(小巧克力或大巧克力)实现目标
如果(小+大*5)<目标:
返回-1
#在这种情况下,大条就足够了,剩下的目标可能需要也可能不需要较小的单位
elif((大*5)>目标):
返回目标%5
#其他情况下使用的小钢筋数量
其他:
返回目标-大*5

您认为您的代码有效吗?你认为
小的
大的
有什么价值?我尝试过的大多数情况下都是这样,但网站(codingbat.com)尝试了多种情况。我猜其中一个肯定引起了一个无限循环,但我不知道它可能是什么。对不起,我是新来的。你对小的和大的价值观是什么?你能给我这个练习的链接吗?当然!你的代码在功能上是正确的,但是有一个测试用例有一个巨大的目标,你的代码重复地从中减去5花费的时间太长了。只是想知道,这样我就不会再犯同样的错误:你可能知道它为什么会出错吗?@EdwardRoy“Timed Out”jsut表示你的代码花费的时间太长了。但是你的代码很好,只是网站看起来很严格,所以需要另一种方式;但是你的代码很好,非常感谢!代码没有遗漏任何其他内容,因为
if
中有一个
返回
,所以“else”或“not”不起作用matter@azro抱歉,这太愚蠢了。我将删除编辑。