Code Review with Exercise 12. Stocking Out



<Below this line, add a link to the EXACT exercise that you are stuck at.>

not understanding what is wrong with this code, says it’s returning wrong amount.

def compute_bill(food):
  total = 0
  for key in food:
    if stock[key] > 0:
      total += prices[key]
      stock[key] = -1
  return total


so there are 32 oranges in stock (at the beginning, agree?)

when a customer buys 1 orange, you change the stock to -1, you should decrease the stock by one.

no we went from 32 to -1 oranges in stock even though only one orange was sold, so we should have 31 oranges remaining


I fixed the code to

stock[key] -= stock[key]

however, im still getting the error;

calling compute_bill with a list containing 2 apples, 3 oranges and 5 bananas resulted in 5.5 instead of the correct 24.5


that will reduce the stock to zero. We just want to decrease the stock of a product (key) by one


gotcha, changed it to

stock[key] -= 1

and it’s working, thank ya


very good, do you also understand why this works?


i get it because when you do

stock[key] -= stock[key]
its essentially saying stock[key] - stock[key] (i think) , so its gonna cancel it out

then if we do stock[key] = -1
we are just reassigning the stock[key] to -1

so if we say stock[key] -= 1
its gonna properly take away one of the stock


its essentially the same as updating a variable:

x = 5
x -= x  # 0, same as x = x - x
x = -1 # -1, we updated x with a value of -1
x -= 1 # decrease by one, -2 in this case, given x was minus one

except now we update a value belonging to key in dictionary


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.