为了账号安全,请及时绑定邮箱和手机立即绑定

为了获得最大数量的产品并给予一定的金钱限制

为了获得最大数量的产品并给予一定的金钱限制

炎炎设计 2023-10-18 16:12:24
问题是给出一个产品价格列表,如 [2,3,5,1,1,2,1] 和预算为 5,输出应该是可以购买的最大产品数量。对于这个是 4 ([1,1,2,1])我的代码如下,有时它可以工作,但对于像[2,3,5,1]这样的价格,预算= 7,它应该是3,但它是2。你们能帮忙检查我代码的哪一部分是错误的吗?谢谢def getMaximumOutfits(money,outfits):  result = []  spent = 0  max_length = 0  for i in range(len(outfits)):      spent+=outfits[i]      if spent <=money:          if i!=len(outfits)-1:              result.append(outfits[i])          else:              result.append(outfits[i])              if max_length < len(result):                  max_length = len(result)      else:          if max_length<len(result):              max_length = len(result)          result=[]          spent = outfits[i]          if spent <= money:              result.append(outfits[i])  print(max_length)
查看完整描述

2 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

在运行循环之前,将价格从最小到最大排序。对于您的示例,它先添加 2,然后添加 3,然后添加 5,发现大于 7,因此返回 2。如果按顺序排列,则会添加 1、2 和 3,然后再添加到 5。



查看完整回答
反对 回复 2023-10-18
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

您设置程序来尝试每个选项的方式是违反直觉的。如果先对列表进行排序,则无需每次都从头开始重试,只需浏览列表一次。您可以通过在开始处放置 来非常简单地完成此操作outfits=sorted(outfits)。这消除了对大部分代码的需求,因为最便宜的选项永远是第一个。


您可以做出的另一个改进是,您实际上不需要跟踪诸如花费和结果之类的事情。由于您唯一关心的是您可以购买多少商品,因此您可以创建一个变量(从 0 开始),并在每次您买得起另一件商品时为其添加 1。


另一个可能的改进是,您不必每次都检查,if spent<money只需将钱视为“余额”,然后从总数中减去您花费的金额,直到钱小于 0。


只是作为一个快速的侧面观点,而不是写


for i in len(outfits):

    spent+=outfits[i]       

您可以迭代列表本身


for i in outfits:

    spent+=i

并得到相同的结果


您的最终代码应该如下所示:


def getMaximumOutfits(money,outfits):

    outfits=sorted(outfits)#sorts the list from smallest --> biggest

    items=0

    max_size=0

    for i in outfits: #goes through each element in the outfit list

        money-=i   #subtracts the cost of this item from the remaining money

        if money<0: #if they couldn't afford this item

            max_size=items #the amount of items they had before this one is their max

        else: #if they can afford this item

            items+=1 #the total items goes up by 1

    return(max_size)

print(getMaximumOutfits(7,[2,3,5,1]))

>>> 3

有任何问题请随时询问我(们 ;)


查看完整回答
反对 回复 2023-10-18
  • 2 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信