You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于餐单、食谱及营养数据库实现总摄入卡路里计算函数mealCal?

How to Implement the mealCal Function for Calculating Total Calorie Intake

Hey there! Let's break this down step by step to make it easy to follow as a beginner. We'll build on the code you started with, but refactor it to be more readable and efficient using dictionaries (which are perfect for quick lookups).

Step 1: Convert the Nutrient Database to a Lookup Dictionary

First, let's turn your contra, split, and calories functions into a single function that creates a dictionary mapping food names to their per-serving calorie counts. This will let us quickly look up how many calories are in any ingredient.

def get_food_calories(db):
    food_calorie_map = {}
    for entry in db:
        # Split the food name from its nutrient values
        food_name, nutrient_str = entry.split(":")
        # Convert nutrient values from strings to integers
        fat, protein, carbs = map(int, nutrient_str.split(","))
        # Calculate total calories per serving using the given formula
        total_calories = (fat * 5) + (protein * 5) + (carbs * 9)
        food_calorie_map[food_name] = total_calories
    return food_calorie_map

For example, this function will turn your sample db into a dictionary where food_calorie_map["Cabbage"] returns 30 (the calculated calories for one serving of cabbage).

Step 2: Convert Recipes to a Meal-to-Ingredients Dictionary

Next, we'll create a dictionary that maps each meal name to its ingredients and the number of servings needed for each. This makes it easy to look up what's in any meal from your meal list.

def get_recipe_ingredients(recipes):
    recipe_map = {}
    for recipe in recipes:
        # Split the meal name from its ingredient list
        meal_name, ingredient_str = recipe.split(":")
        ingredients = {}
        # Split each ingredient entry and parse the food name and count
        for item in ingredient_str.split(","):
            food, count = item.split("*")
            # Use strip() to handle any accidental spaces in the input
            ingredients[food.strip()] = int(count)
        recipe_map[meal_name.strip()] = ingredients
    return recipe_map

Using your sample recipes, this will create a dictionary where recipe_map["T-Bone"] returns {"Carrot": 2, "Steak Meat": 1}.

Step 3: Build the mealCal Function

Now we'll combine the two dictionaries above to calculate the total calories from the meal list. We'll iterate through each item in the meal, calculate its total calories, and add it to the running total.

def mealCal(meal: list[str], recipes: list[str], db: list[str]):
    # Get our lookup dictionaries ready
    food_calories = get_food_calories(db)
    recipe_ingredients = get_recipe_ingredients(recipes)
    
    total_calories = 0
    
    # Calculate calories for each item in the meal
    for meal_item in meal:
        # Get the ingredients for this meal (default to empty dict if not found)
        ingredients = recipe_ingredients.get(meal_item, {})
        meal_item_calories = 0
        
        # Calculate calories for each ingredient in the meal
        for food, count in ingredients.items():
            # Multiply per-serving calories by the number of servings
            meal_item_calories += food_calories.get(food, 0) * count
        
        # Add this meal's calories to the total
        total_calories += meal_item_calories
    
    return total_calories

Test the Function with Your Sample Input

Let's verify it works with your example values:

# Sample input values
meal = ["T-Bone", "T-Bone", "Green Salad1"]
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"]
db = ["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5", "Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"]

# Calculate and print total calories
print(mealCal(meal, recipes, db))  # Output: 1500

This works because:

  • Each T-Bone has (95 * 2) + (215 * 1) = 405 calories, so two of them add up to 810
  • Green Salad1 has (30 *10) + (95*2) + (40*5) = 690 calories
  • Total: 810 + 690 = 1500

内容的提问来源于stack exchange,提问作者Joshua Bradley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 03:12:37