Python实现make_bricks与make_chocolate问题

这篇博客介绍了两个编程问题:make_bricks和make_chocolate。这两个问题涉及到使用不同大小的元素(砖块或巧克力)来达到目标长度或重量。解决思路是在可能的情况下优先使用大元素。提供的Python代码实现了这一策略,并通过了测试用例。make_bricks返回是否能用给定的小砖和大砖完成目标长度,而make_chocolate返回在优先使用大巧克力条的情况下,达到目标重量所需的最小小巧克力条数,或者在无法达成目标时返回-1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值