while循环命题添加

while-loop proposition adding

我想编写一个有点复杂的代码,建议用户在总成本低于预算的情况下将一些产品添加到他的购物车中,但是我 运行 遇到了一个问题,当我输入少量预算(仍然可以包括酱汁等小产品),代码进入无限循环或根本不起作用,想知道如何修复我的代码

productlist = ['Sushi', 'Spirulini', 'Sause', 'Cabbage']
pricelist = [56, 31, 4, 9]
totalcost = 0
budget = 10

proposal_list = []
i = 0

while totalcost < budget:
  if i >= len(pricelist):
    i = 0
  elif (pricelist[i] + totalcost) <= budget:
    totalcost += pricelist[i]
    proposal_list.append(productlist[i].lower())
    joint = ', '.join(proposal_list)
    i += 1
  elif (pricelist[i] + totalcost) > budget:
    continue 

print (f'You can also add: {joint} to your cart for a great discount!\nTotal cost will be: {totalcost}')

问题是您遇到 totalcost < budgetpricelist[i] + totalcost > budget 都为真的情况(即,您还有一些钱,但不够 productlist[i]),但是你既不改变 i 也不改变 totalcost,所以你永远循环着你买不起 prodouctlist[i].

的事实

当您再也买不起任何产品时,您绝不会真正退出循环;你似乎假设你将能够花费 正好 budget 美元。

这是一个示例,使用 for 循环,尽可能购买 many 每件商品(greedy 方法),这样你每一项只考虑一次。

totalcost = 0

for product, price in zip(productlist, pricelist):
    while totalcost + price <= budget:
        proposal_list.append(product.lower())
        totalcost += price

对于某些价目表,这也会花费尽可能多的预算。 (这基本上是 change-making problem 的另一种形式。)对于其他价目表,您在重新考虑每个项目之前尝试至少购买每个项目的方法可能会产生不同的结果。