'while-loop proposition adding
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}')
Solution 1:[1]
The problem is that you get into a situation where both totalcost < budget and pricelist[i] + totalcost > budget are true (i.e., you have some money left, but not enough for productlist[i]), but you don't change either i or totalcost, so you loop forever on the fact that you can't afford prodouctlist[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.
totalcost = 0
for product, price in zip(productlist, pricelist):
while totalcost + price <= budget:
proposal_list.append(product.lower())
totalcost += price
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chepner |
