CondingBat Python Puzzle Results In "Timed Out"
I am trying to solve this CodingBat problem: 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
Solution 1:
The failure is caused by time it takes to do this test:
makeChocolate(1000, 1000000, 5000006)
Even though the other tests can pass, once one test times out, the report shows all tests as timing out. To see this is true, change xrange(big)
to xrange(big if big < 101 else 0)
and you will see every test pass except for the one above.
Web based evaluators need timeouts like these for performance reasons . It must be that the Python timeout allows for less loops than the Java timeout.
Here is non looping solution that passes:
def make_chocolate(small, big, goal):
big *= 5
if big + small < goal or small < goal%5:
return -1
small = goal - big
return small%5 if small < 0 else small
A slightly different solution is needed for Java due to how it treats the modulo for negative numbers.
public int makeChocolate(int small, int big, int goal) {
big *= 5;
if (big + small < goal || small < goal%5)
return -1;
small = goal - big;
return small < 0 ? (big+small)%5 : small;
}
Solution 2:
This is clunky, but it works:
def make_chocolate(small, big, goal):
bigbars=goal//5
if bigbars<=big:
smallgoal=goal-(bigbars*5)
if smallgoal>=0 and smallgoal<=small:
return smallgoal
if smallgoal>small:
return -1
if bigbars>big:
smallgoal=goal-(big*5)
if smallgoal<=small:
return smallgoal
if smallgoal>small:
return -1
Solution 3:
You could simply do it this way:
def make_chocolate(small, big, goal):
noOfBigs = big if(5 * big <= goal) else goal / 5
return goal - (noOfBigs * 5) if small >= (goal - (noOfBigs * 5)) else -1
Solution 4:
def make_chocolate(small, big, goal):
big = big*5
if (goal >= big) and (small >= goal - big):
return goal - big
if (goal < big) and (small >= goal % 5):
return goal % 5
return -1
Solution 5:
Seems like cleaner logic if you first reduce Big value to the number you'll actually use:
def make_chocolate(small, big, goal):
while big * 5 > goal:
big -= 1
if (goal - (big * 5)) <= small:
return goal - (big * 5)
else:
return -1
Post a Comment for "CondingBat Python Puzzle Results In "Timed Out""