문제

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)
도움이 되었습니까?

해결책

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.

다른 팁

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  
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top