Stocking Out Question


#1

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 stock:
if stock[item] > 0:
stock[item] -= 1
for key in food:
total += prices[key]
return total

It tells me that "calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in 2 instead of the correct 7"


#2

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


#3

it is giving me this
Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in 4 instead of the correct 7


#4

I have the same issue. I tried many variations of the code and every time it does not work, while it works fine for other (or so I see :slightly_smiling: ).

Here is my code so hopefully someone will see the issue with it while I can not :confused:


#5

This is the code, which worked for me :slightly_smiling: But indent properly!!
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:
            total+=prices[item]
            stock[item]-=1
        
    return total

#6

Thank you. This code worked for me as well now. Can you just please let me know what does this total+=prices part do as I do not understand this part :slightly_smiling: so I learn something in the process :smiley: thank you


#7

You could probably do this:

    def compute_bill(food):
    total = 0
    for item in food:
        if stock[item] > 0:

You did ok so far but, to add the prices to total and to take away you must use += or -= which makes it accumulate.

            total += prices[item]
            stock[item] -= 1                       
        return total

#8

Thank you. This accumulate part got me a bit confused but I think I understand it know. The code worked after the modifications :slightly_smiling:


#9

if stock[item]>0:
total+=prices[item]

This simply means: "total=total+prices[item]"

So, whenever the stock of some item is greater than 0, we add it's price to the "total" which was earlier set to 0.


#10

What does the stock[item]-=1 do? That part confuses me :frowning: