以获得最大数量的产品,并给出资金限制

2024-05-16 10:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是给出一个产品价格清单,如[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)

Tags: 代码lenif价格resultlengthelsemax
2条回答

在运行循环之前,从最小到最大对价格进行排序。对于您的示例,它添加2,然后添加3,然后添加5,然后看到大于7,所以返回2。如果顺序正确,则在得到5之前,它将添加1、2和3

您设置程序以尝试每个选项的方式是违反直觉的。如果你先对列表排序,你只需要浏览列表一次,而不是每次都从头开始重试。您只需将outfits=sorted(outfits)放在开头就可以做到这一点。 这消除了对大多数代码的需要,因为最便宜的选项总是第一个

你可以做的另一个改进是,你实际上不需要记录花费和结果之类的事情。因为你唯一关心的是你能买多少东西,所以你可以创建一个变量(从0开始),每次你能买得起另一件东西的时候,给它加上1

另一个可能的改进是,不必每次都检查,你只需把钱当作“余额”,然后从总数中减去你花的钱,直到钱少于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

任何问题都可以问;)

相关问题 更多 >