while循环命题添加
我想编写一些复杂的代码,如果用户的总成本低于预算,它会建议用户将一些产品添加到购物车,但我遇到了一个问题,当我输入少量预算金额(仍然可以包括像酱汁这样的小产品),代码进入无限循环或不起作用,想知道如何修复我的代码
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}')
I want to make a bit complex code which will advice user to add some products to his cart if his total cost of it lower than his budget, but I've run into a problem that when I enter a small budget amount (which can still include a small product like sauce), the code goes into an infinite loop or just doesn't work, would like to know how to repair my code
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}')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是你会遇到这样的情况:totalcost
totalcost
totalcost
totalcost
totalcost
totalcost
totalcost
totalcost
totalcost
totalcost
,所以你会永远循环下去,因为你买不起预算
和pricelist[i] + 总成本> Budget
为 true(即,您还剩下一些钱,但不足以购买productlist[i]
),但您不会更改i
或 < code>totalcostproductlist[i]
。当您再也买不起任何产品时,您永远不会真正退出循环;您似乎假设您能够准确地花费
预算
美元。下面是一个使用
for
循环的示例,它会尽可能多地购买每件物品(贪婪方法),这样您只需每个项目都考虑一次。对于某些价目表,这也会花费您尽可能多的预算。 (这基本上是另一种形式的变革问题。)对于其他价目表,在重新考虑每件商品之前尝试购买至少一件商品的方法可能会产生不同的结果。
The problem is that you get into a situation where both
totalcost < budget
andpricelist[i] + totalcost > budget
are true (i.e., you have some money left, but not enough forproductlist[i]
), but you don't change eitheri
ortotalcost
, so you loop forever on the fact that you can't affordprodouctlist[i]
.At no point do you actually exit the loop when you can no longer afford any product; you seem to be assuming that you will be able to spend exactly
budget
dollars.Here's an example, using a
for
loop, that buys as many of each item as you can (a greedy method), so that you only consider each item once.For certain price lists, this will also spend as much of your budget as possible. (This is basically the change-making problem in another guise.) For other price lists, your approach of trying to buy at least one of each item before reconsidering each item could produce a different result.