Skip to content Skip to sidebar Skip to footer

Computing Shopping-list Total Using Dictionaries

I tried calling the total of dictionary values for a shopping list made in list, but error has been coming up and summing to 10.5 instead of 7.5, it is supposed to give out the tot

Solution 1:

You can use list comprehensions ...

sum([ prices[s] for s in shopping_list ])

Solution 2:

I'm assuming you want to compute the total cost of a list of items.

You've got a few issues with your existing code:

  • shopping_list is a dictionary, not a function or class (or "callable"). You can access items within it using shopping_list[key]
  • You're doing for item in foods but you're then assigning to item. This is probably not what you want.
  • key doesn't exist anywhere in your code except for prices[key]

I think you want something like this for your compute_bill function:

def compute_bill(food):
    total =0for item in food:
         total += prices[item]
    return total

You can then call this using compute_bill(shopping_list). This function will now return 7.5 (which is the result you were looking for).

Solution 3:

Your code and everyone else's here has ignored stock, so it can sell more items than are in stock; presumably that's a bug and you're supposed to enforce that restriction. There's two ways:

The iterative approach: for item in food:... check stock[item] is >0 , if yes add the price, decrement stock[item]. But you could simply sum each item-count and compute the min() with stock-count.

More Pythonic and shorter:

# Another test case which exercises quantities > stock
shopping_list = ["banana", "orange", "apple", "apple", "banana", "apple"]

from collections import Counter    
counted_list = Counter(shopping_list)
# Counter({'apple': 3, 'banana': 2, 'orange': 1})

total = 0
for item, count in counted_list.items():
    total += min(count, stock[item]) * prices[item]

or as a one-liner:

sum( min(stock[item],count) * prices[item] for item,count in Counter(shopping_list).items() )

Solution 4:

Your code looks weird, but this works:

def compute_bill(food):
    total = 0for item in food:
        total += prices[item]
    returntotalshopping_list= ["banana", "orange", "apple"] print
compute_bill(shopping_list)

I'm assuming you want to use the prices dict to calculate prices for items in your shopping_list.

If you need any help, ask me.

Post a Comment for "Computing Shopping-list Total Using Dictionaries"