Code Review with Exercise 12. Stocking Out

python

#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/stocking-out-?action=lesson_resume

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



#2

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


#3

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


#4

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


#5

gotcha, changed it to

stock[key] -= 1

and it’s working, thank ya


#6

very good, do you also understand why this works?


#7

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


#8

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


#9

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