简体   繁体   中英

Codingbat make_bricks timed out with while loop in python

My goal is: We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.

My code is:

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

In my IDLE this works well, but codingbat resulted in TimedOut. Is it happenning because for big numbers while loop is too slow? I am using python 3.2.5.

EDIT:

I tried another code:

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

But with same issue.

Okay I know why it doesn't work. Your code would work. But if there is a loop with about ~229500 (I tried to find the limit value on codebat, but sometime it timeout at this value, sometimes it doesn't. But the value is arround 230k) And as you said : One time out, and every value becomes time out. So to sum up, your code is working, but for the make_bricks(1000000, 1000, 1000100) → True test, there is a too big loop, and Codebat crashes.

So if you want to make it work on Codebat, you have to get rid of the while statement :

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 return the whole division . I think this is enought. (this should be the alst edit sorry)

I had a similar problem. I think CodingBat doesn't support += , -= , etc. So if you change the lines containing that, you should not get a Timed Out. For example, small -= 1 would become small = small - 1 . I tested it and it worked on my end, in CodingBat.

Just categorise the if statements according to whether the big bricks are cumulatively bigger or smaller than the goal.

def make_bricks(small, big, goal):
  if (5*big) >= goal:
    return (goal%5) <= small
  if (5*big) < goal:
    return (goal - 5*(big)) <= small

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM