Calculating the entire shopping list using dictionaries

I tried to name the total number of dictionary values ​​for the shopping list made in the list, but the error approached and added up to 10.5 instead of 7.5, it should give the total price of the items in the list, any list,

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:
        item = shopping_list(prices[key])
        total += item
    return total
shopping_list = ["banana", "orange", "apple"]  
0
source share
4 answers

You can use lists ...

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

+3
source

I assume that you want to calculate the total cost of a list of items.

You have several problems with existing code:

  • shopping_list is a dictionary, not a function or class (or "called"). You can access the elements inside it usingshopping_list[key]
  • for item in foods, item. , , , .
  • key , prices[key]

, - compute_bill:

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

, compute_bill(shopping_list). 7.5 ( , ).

+2

stock, , ; , , . :

: for item in food:... check stock[item] is > 0, , , stock[item]. min() count-count.

Pythonic :

# 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]

:

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

Your code looks weird, but it works:

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

shopping_list = ["banana", "orange", "apple"] print
compute_bill(shopping_list)

I assume that you want to use pricesdict to calculate product prices at shopping_list.

If you need help, ask me.

0
source

Source: https://habr.com/ru/post/1627213/


All Articles