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

如何编写Python函数totalcalories计算各食谱的总热量

食谱总热量计算实现方案

原代码问题说明

你写的代码仅做了字符串存在性判断,没有完成「解析热量映射、拆分食谱食材用量、累加计算总热量」的核心逻辑,所以无法得到预期结果。

最简实现代码

def totalcalories(recipes: list[str], tcal: list[list[str]]):
    # 第一步:把tcal转成{食材名: 热量}的字典,方便快速查询
    cal_dict = {}
    # 示例中tcal外层套了一层列表,所以取tcal[0]遍历食材热量条目
    for item in tcal[0]:
        # 按冒号拆分食材名和热量值,strip()去掉前后多余空格
        food, cal = item.split(":")
        cal_dict[food.strip()] = int(cal.strip())
    
    result = []
    # 第二步:遍历每个食谱计算总热量
    for recipe in recipes:
        # 按冒号拆分菜名和食材部分
        _, food_part = recipe.split(":")
        # 按逗号拆分得到每个「食材*用量」条目
        food_items = food_part.split(",")
        total = 0
        for food_item in food_items:
            # 按星号拆分食材名和用量
            food_name, count = food_item.split("*")
            food_name = food_name.strip()
            count = int(count.strip())
            # 累加当前食材的总热量:用量 * 单位热量
            total += count * cal_dict[food_name]
        # 转成字符串存入结果列表
        result.append(str(total))
    
    # 按预期格式返回:双引号包裹、逗号分隔
    return ','.join(f'"{x}"' for x in result)

# 示例输入测试
if __name__ == "__main__":
    res = 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"]]
    )
    print(res)

运行代码输出结果为:"22295","690","405",完全符合预期。

核心逻辑说明

  1. 构建热量字典:把原始的"食材:热量"字符串转成字典结构,后续查询食材热量只需要1次查询就能拿到结果,不用每次遍历整个tcal列表,效率更高
  2. 食谱字符串拆分:
    • 先按:把食谱字符串拆成菜名和食材列表两部分,不需要菜名的话可以直接忽略前半段
    • 按,拆分得到每个食材*用量的独立条目
    • 每个条目再按*拆分得到食材名和用量,调用strip()去掉字符串前后多余的空格,避免匹配不到热量字典的key
  3. 热量累加:每个食材的用量乘以单位热量,全部相加就是当前食谱的总热量
  4. 格式处理:最后把所有结果用双引号包裹,逗号分隔,和要求的输出格式完全对齐

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:24:04