Python实现make_bricks与make_chocolate问题
问题描述
1:make_bricks
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. This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
2:make_chocolate
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 small bars to use, assuming we always use big bars before small bars. Return -1 if it can’t be done.
make_chocolate(4, 1, 9) → 4
make_chocolate(4, 1, 10) → -1
make_chocolate(4, 1, 7) → 2
解决思想
use big bars before small bars(尽可能的使用长的)
实现代码
def make_bricks(small, big, goal):
if 5big<goal:
s = goal-5big
if s<=small:
return True
else:
s = goal%5
return s<=small
return False
测试结果:
def make_chocolate(small, big, goal):
if 5big<goal:
s = goal-5big
if s<=small:
return s
else:
s = goal%5
return (s if(s<=small) else -1)
return -1
测试结果: