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

如何不使用额外导入编写gathercal函数计算食谱总热量

最简gathercal函数实现方案

前置工具函数(已有实现)

def rdict(recipes):
    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

def totalcal(data):
    calorie_dict = {}
    for el in data:
      food, values = el.split(':')
      a, b, c = values.split(',')
      calories = (int(a) * 5) + (int(b) * 5) + (int(c) * 9)
      calorie_dict[food] = calories
    return calorie_dict

新函数实现

直接复用上述两个工具函数即可,无需引入任何额外依赖,完全符合不使用import、lambda、collections相关方法的要求:

def gathercal(recipes, data):
    # 解析得到每个餐品对应的食材用量字典,示例入参recipes为嵌套列表,需先提取第一层
    recipe_map = rdict(recipes[0])
    # 解析得到每种食材对应的单位热量字典
    cal_map = totalcal(data)
    result = dict()
    # 遍历所有餐品计算总热量
    for dish_name, food_list in recipe_map.items():
        dish_total = 0
        for food_name, use_count in food_list.items():
            dish_total += cal_map[food_name] * use_count
        result[dish_name] = dish_total
    return result

验证说明

测试入参

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

# 注:原示例中给出的键值对格式data是totalcal执行后的返回结果,totalcal的原始入参为字符串列表,格式如下:
data = [
    "Cabbage:6,0,0",
    "Carrot:19,0,0",
    "Fatty Pork:0,0,245",
    "Pineapple:8,0,0",
    "Steak Meat:0,43,0",
    "Rabbit Meat:0,45,0"
]

运行后得到的餐品总热量和示例给出的计算结果完全匹配。

输出结果

调用gathercal(recipes, data)返回的字典如下:

{
    "Pork Stew": 22295,
    "Green Salad1": 690,
    "T-Bone": 405
}

内容的提问来源于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 22:27:05