2016-07-25 72 views
0

我的目标是: 我们想制作一排长度为英寸的砖块。我们有许多小砖(每个1英寸)和大砖(每个5英寸)。如果可以通过从给定的砖块中选择目标来实现目标,则返回True。Codingbat make_bricks用python中的while循环超时

我的代码是:

def make_bricks(small, big, goal): 
    if small + 5*big < goal: 
    return False 
    elif small + 5*big == goal: 
    return True 
    else: 
    while small > 0: 
     small -= 1 
     goal -= 1 
     if goal % 5 == 0 and big >= goal/5: 
     return True 
    return False 

在我空闲这个效果很好,但codingbat导致TIMEDOUT。这是否是因为大数字while循环太慢?我正在使用Python 3.2.5。

编辑:

我尝试另一个代码:

def make_bricks(small, big, goal): 
    if small ==0: 
    if goal % 5 == 0 and goal/5 <= big: 
     return True 
    else: 
     return False 
    elif small + 5*big < goal: 
    return False 
    elif small + 5*big == goal: 
    return True 
    else: 
    while small > 0: 
     small -= 1 
     goal -= 1 
     if goal % 5 == 0 and big >= goal/5: 
     return True 
    return False 

但随着同样的问题。

+0

什么值'small'导致暂停? – Carcigenicate

+0

超时是在每一列,但我读过的地方,当一个结果超时,所有将导致超时。但是我看到你的问题更深入,你指出了。这个问题可能是当小== 0.我试试。 – Bobesh

+0

没有工作,同样的问题 – Bobesh

回答

0

好吧我知道它为什么不起作用。你的代码可以工作。但如果有一个loop与约229500(我试图找到在codebat上的限制值,但有时超时在这个值,有时它不,但价值是230k周围)正如你所说:一次性,每个值都会超时。总结一下,你的代码正在工作,但是对于make_bricks(1000000, 1000, 1000100) → True测试,有一个太大的循环,Codebat崩溃。

所以,如果你想它Codebat工作,你必须摆脱while声明:

def make_bricks(small, big, goal): 
    if small>=5 : 
     if (goal - (big + (small // 5 - 1)) * 5) <= (small % 5 + 5): 
      return True 
     else: 
      return False 
    else : 
     if (goal - big * 5) % 5 <= (small % 5) : 
      return True 
     else : 
      return False 

small//5回报whole division。 我认为这已经足够了。 (这应该是阿尔斯编辑抱歉)

+0

那么thx,但我的目标不仅仅是解决它,而是发现一个错误。你能看到我的代码中有任何问题吗? – Bobesh

+0

@Bobesh你的代码应该工作。逻辑工作,没有错字。可能是一个代码禁止的问题,它不喜欢while语句,而不是几次迭代(不会有无限循环重载它们)。但我真的相信你做得对 – pwnsauce