Compute bill for a super market
-
07-07-2021 - |
Question
Below is the code to compute the bill for the supermarket. Everything is ok but the issue is that I am told that this solution would not work if the input is only apple.
I do believe that the value of apple should be 0 since apples are not in the stock but still I believe there is something that I am not doing correct. Please help.
groceries = ["apple","banana", "orange",]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(food):
total = 0
for item in food:
tot = prices[item] * stock[item]
print item, tot
total += tot
return total
computeBill(groceries)
Solution
I am just going to go off on my own with this answer and make suggestions, since it seems the specifications for your computeBill
functionality are not well defined.
If the items are not in stock, and your instructor says it is not acceptable to return 0
in this case, then your other options are to raise an exception, or a sentinel value indicating an error state.
def computeBill(food):
total = 0
for item in food:
stock_count = stock[item]
if stock_count == 0:
raise ValueError("item %s is out of stock" % item)
tot = prices[item] * stock_count
print item, tot
total += tot
return total
Or if you don't want to raise an exception, you could return -1
if you feel that is not a valid total anyways:
if stock_count == 0:
return -1
There are some other problems with the function in how it calculates the list vs stock, but you said you didn't care about those right now.
OTHER TIPS
I don't know why this wouldn't work. If your input was ['apple']
, this would happen:
computeBill(['apple'])
total = 0
item = 'apple'
tot = price['apple'] * stock['apple']
tot = 2 * 0
print 'apple',0
total += 0
return total
return 0
Unless they expect to be able to pass in a single item without wrapping it in a list, so calling `computeBill('apple'). In that case, you'd have to do a type check at the beginning of your function. That could look like this
if type(food) is not list:
food = [food]
def compute_bill(food):
total=0
for item in food:
if stock[item]>0:
tot=prices[item]
total+=tot
stock[item]-=1
return total