开发者

A Python Problem: A function that calculates a value from two given dictionaries

This is a tutorial problem that I have come across and after learning Python for about a month now, this really challenges me since I haven't encountered this type of problem before.

I want to calculate the total cost of a given 'id' from the 2 dictionaries.

Below shows my dictionaries:

a = {'HIN3': ('Plastic Wrap', 50), 'GIN2': ('Cocoa', 80), 'LIN1': ('Bayleaf', 25), 'TIN6': ('Powder Scent': 210), 'QIN8': ('Color 55': 75)}

the 1st value is the id, then the 2nd contains of pair list consisting the name and the cost of it.

b = {'candy1': ('Choco fudge', [('HIN3', 1), ('GIN2', 5)]), 'candy2': ('Mint Lolly', [('LIN1', 3), ('GIN2', 1), ('HIN3', 1)]), 'candy3': ('MILK', [('HIN3', 1), ('TIN6', 4), ('QIN8', 1)])}

where the 1st value is the id of the dict b, the 2nd is a list which contains the name and the ingredients开发者_开发技巧 needed to produce the product.

Now i need to create a function (get_cost(id))that would give the total cost given the id of dict b.

For example, the outcome of get_cost('candy1') would be 450 since it needs 1 of HIN3 (50) and 5 of GIN2 (5*80 = 400) so the cost is 50+400 = 450. Note that i want to return the cost as integer.


First, an easy-to-follow function:

def getCost(id):
    total_cost = 0
    ingredients = b[id][1] # Second element of tuple is ingredient list

    for ingredient, amount in ingredients:
        total_cost += a[ingredient][1] * amount

    return total_cost

Now, a cute one-liner:

def getCost(id):
    return sum(a[ingredient][1] * amount for ingredient, amount in b[id][1])

I didn't test these, if you find problems, let me know. Or better still, fix them yourself :) after all, tutorial problems are for you to explore! Play around, get it wrong, fix it, try again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜