In Python, if you have a dictionary (Groovy calls it a map) like the stock dictionary defined below… you can subtract from it pretty easily. In the example below I had a function called compute_bill, at the end of which I subtract the stock item that is used in the total calculation. So we sold an orange, we remove 1 orange from our stock.
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
if(stock[item] > 0):
print prices[item]
total += prices[item]
stock[item] = stock[item] - 1
return total
In the iteration I make a call for item in food:
and do a stock[item] (our iterator) is stock[item] -1
That action automatically changes the value in the dictionary. So if I had an orange with a stock of 32, and I ran compute_bill(shopping_list), the stock on oranges will become 31.
To do this without a loop, you could simply call:
stock[‘orange’] – 3 and that would subtract 3 from the value of orange.