Home > Mobile >  How to use two given inputs in a function and get the total
How to use two given inputs in a function and get the total

Time:11-20

So I'm trying to create a function totalcalories(recipes, tcal) where recipes would refer to the ingredients that is going to be provided while tcal is the amount of calories that each ingredient contains...

I have figured out a way to find tcal from the given input but I have no idea how to extract the information from recipes into tcal

So like if the input is

`totalcalories(recipes = ["Pork Stew: Cabbage*5,Carrot*1, Fatty Pork*10",

"Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",

"T-Bone: Carrot*2,Steak Meat*1"],

tcal = [["Cabbage:30", "Carrot:95", "Fatty Pork:2205",


 "Pineapple:40", "Steak Meat:215", "Rabbit Meat:225"])

And so I expect the output to return

"22295","690", "405"

So 22295 is the result of the recipe Pork Stew, which is Cabbage(30) from tcal times 5, which is 150, and 1 carrot, which is 95 and 10 Fatty Pork, which is 2205 each. Adding all three numbers give 22295.

The same principle applies for every recipe in recipes, where Green Salad would return 690 and T-bone 405...

What I'm trying to do is to write a function that will return the total calories like the examples I just provided...

Here is my attempt at it... which clearly doesn't work..

def totalcalories(recipes: list[str], tcal: list[str]):
    g = []
    for x in tcal:
        if x in recipes:
            g.append(x)
    return g
print(totalcalories(["T-Bone", "T-Bone", "Green Salad1"],["Pork Stew:Cabbage*5,Carrot*1,Fatty Pork*10",
"Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
"T-Bone:Carrot*2,Steak Meat*1"]))

What should I write to make my code work...

Please write the code in the simplest way possible. I would like to take things really slow and understand what the code means so yea, please picture yourself teaching a beginner when you resolve my issue, so that I can also learn along

Thank you! `

CodePudding user response:

The input data structure is parseable (after all, there's always a way) but would be better if it was in the form of a dictionary. So, this code converts your structure into dictionaries and then goes on to show how much easier it is to process once they're in that form.

recipes = ["Pork Stew: Cabbage*5,Carrot*1, Fatty Pork*10",
           "Green Salad1:Cabbage*10,Carrot*2,Pineapple*5",
           "T-Bone: Carrot*2,Steak Meat*1"]
calories = ["Cabbage:30", "Carrot:95", "Fatty Pork:2205",
            "Pineapple:40", "Steak Meat:215", "Rabbit Meat:225"]

def cdict(): # convert calories list to dictionary
    d = dict()
    for e in calories:
        e_ = e.split(':')
        d[e_[0]] = int(e_[1])
    return d

def rdict(): # convert recipe list to dictionary
    d = dict()
    for r in recipes:
        i = dict()
        r_ = r.split(':')
        for c_ in r_[1].split(','):
            i_ = c_.split('*')
            i[i_[0].strip()] = int(i_[1])
        d[r_[0]] = i
    return d

recipes_d = rdict()
calories_d = cdict()

for k, v in recipes_d.items():
    tcal = 0
    for k_, v_ in v.items():
        tcal  = calories_d[k_] * v_
    print(f'Recipe {k} has {tcal} calories')

CodePudding user response:

You can define 2 patterns: one to capture the name of the recipe, the second to capture each single ingredient in the recipe itself.

pattern_recipe = re.compile(r'([^\:]*):.*')
pattern_ingredients = re.compile(r'([^\*\:,]*)\*(\d*),?', re.DOTALL)

Now, process each line of your totalcalories_recipes list create a dictionary which is keyed with the name of the recipe and element the list of ingredients with calories:

recipes_dict = {pattern_recipe.findall(x)[0]:
                   [(ingredient.strip(), int(calories)) for ingredient, calories in pattern_ingredients.findall(x)] 
                for x in totalcalories_recipes}

To be clear, the nested list comprehension cleans ingredient name, stripping spaces, and casts calories into int.

At this point, your recipes_dict should look as follows:

 {'Pork Stew': [('Cabbage', 5), ('Carrot', 1), ('Fatty Pork', 10)], 'Green Salad1': [('Cabbage', 10), ('Carrot', 2), ('Pineapple', 5)], 'T-Bone': [('Carrot', 2), ('Steak Meat', 1)]}

In a similar fashion, you can get a dictionary from your tcal list:

tcal_dict = {x[0]:int(x[1]) for x in [re.findall("([^\:]*)\:(\d )", x)[0] for x in tcal]}

Now you are in business! Looping through each recipe in recipes_dict, you can calculate the calories by recipe:

{recipe[0]:sum([ingredient[1] * tcal_dict[ingredient[0]] for ingredient in recipe[1]]) for recipe in recipes_dict.items()}

OUTPUT:

{'Pork Stew': 22295, 'Green Salad1': 690, 'T-Bone': 405}
  • Related