Python實現make_bricks與make_chocolate問題

資源分享小白兔發表於2020-10-15

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-5
big
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-5
big
if s<=small:
return s
else:
s = goal%5
return (s if(s<=small) else -1)
return -1

測試結果:
在這裡插入圖片描述

相關文章