如何从咖啡机资源字典中扣除所选咖啡原料并生成剩余资源报告?
解决方案
完整可运行代码
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } resources = { "water": 300, "milk": 200, "coffee": 100, } def print_resource_report(): """打印当前咖啡机剩余资源""" print(f"剩余资源:") print(f"Water: {resources['water']}ml") print(f"Milk: {resources['milk']}ml") print(f"Coffee: {resources['coffee']}g") def check_resources(ingredients): """检查资源是否足够制作所选饮品,返回布尔值""" for item, amount in ingredients.items(): if resources[item] < amount: print(f"抱歉,{item}不足。") return False return True def deduct_resources(ingredients): """从资源中扣除制作饮品所需的原料""" for item, amount in ingredients.items(): resources[item] -= amount # 获取用户选择 user_choice = input("What would you like? (espresso/latte/cappuccino): ").lower() # 处理用户请求 if user_choice in MENU: drink_details = MENU[user_choice] # 先检查资源是否足够 if check_resources(drink_details['ingredients']): # 扣除对应原料 deduct_resources(drink_details['ingredients']) print(f"已制作{user_choice},请取餐!") # 打印剩余资源报告 print_resource_report() else: print("无效的选择,请输入espresso、latte或cappuccino。")
关键逻辑说明
- 资源检查:
check_resources函数遍历所选饮品的原料,逐一对比当前资源量,若有原料不足则提示并终止制作流程。 - 资源扣除:
deduct_resources函数遍历原料列表,从全局resources字典中减去对应用量,确保资源数据实时更新。 - 报告打印:
print_resource_report函数格式化输出剩余资源,清晰展示水、牛奶、咖啡的剩余量。 - 异常规避:通过判断用户输入是否在
MENU的键集合中,避免非法输入导致的KeyError;同时仅遍历饮品实际需要的原料,解决了espresso无牛奶时的取值报错问题。
原代码问题修正
- 原
format_data函数依赖全局变量而非参数,改为使用独立函数封装单一职责逻辑。 - 修正了
cost的取值路径(原错误取到ingredients下,实际应在饮品层级)。 - 补充了资源检查、扣除及报告打印的核心逻辑,实现完整的咖啡机流程。
内容的提问来源于stack exchange,提问作者gringocoder
相关产品推荐
相关产品推荐

