Files
2026-07-29 16:31:08 +08:00

106 lines
4.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 1-10 课课堂练习Agent 配置管理器
#
# 完成要求:
# 1. 根据注释完成字典的创建、读取、修改、删除、遍历和嵌套操作。
# 2. 使用有意义的英文蛇形变量名。
# 3. 读取可能不存在的键时使用 get() 或先使用 in 判断。
# 4. 删除键前确认键存在,或为 pop() 提供默认值。
# 5. 不要删除题目注释。
# 6. 完成后运行本文件并核对预期结果。
# 练习一:创建字典 agent_config包含以下键值对
# model"gpt-5"
# temperature0.7
# max_tokens2000
# enabledTrue
# 练习二:输出以下信息:
# 1. 完整字典;
# 2. 键值对数量;
# 3. 使用方括号读取 model
# 4. 使用 get() 读取 temperature。
# 练习三:使用 get() 读取不存在的 timeout并提供默认值 30。
# 将结果保存到 timeout输出该变量。
# 确认执行后 timeout 键仍未自动加入 agent_config。
# 练习四:完成以下添加和修改:
# 1. 添加 timeout值为 60
# 2. 把 temperature 修改为 0.3
# 3. 使用 update() 添加 retries=3并把 max_tokens 修改为 4000。
# 练习五:完成以下成员判断:
# 1. 判断是否存在 model 键,保存到 contains_model
# 2. 判断是否存在 timeout 键,保存到 contains_timeout
# 3. 判断 "gpt-5" 是否直接存在于字典键中,保存到 model_value_is_key。
# 观察第三个结果,理解 in 默认检查键。
# 练习六:使用 pop() 删除 retries。
# 将被删除的值保存到 removed_retries。
# 为 pop() 提供默认值 None避免键不存在时报错。
# 练习七:使用 in 判断 timeout 是否存在。
# 如果存在,使用 del 删除 timeout。
# 练习八:分别完成三种遍历:
# 1. 遍历并输出所有键;
# 2. 遍历并输出所有值;
# 3. 使用 items() 同时遍历键和值格式为“modelgpt-5”。
# 练习九:创建嵌套字典 nested_config
# model 对应一个内部字典,包含 name="gpt-5"、temperature=0.7
# runtime 对应一个内部字典,包含 timeout=30、enabled=True。
# 输出嵌套的模型名称和超时时间。
# 练习十:创建 Agent 列表 agents包含两个字典
# 第一条name="代码助手"、model="gpt-5"、enabled=True
# 第二条name="搜索助手"、model="o3"、enabled=False。
# 使用 for 遍历并输出每个 Agent 的名称、模型和启用状态。
# 练习十一:创建字典 agent_profile
# name="代码助手"
# tools=["搜索", "计算"]。
# 向 tools 列表追加 "写作",再输出工具列表。
# 练习十二:使用 copy() 创建 agent_config 的独立浅复制 backup_config。
# 在 backup_config 中把 model 修改为 "o3"。
# 分别输出两个字典,确认原字典的 model 仍为 "gpt-5"。
# 练习十三:使用 30 个等号输出分隔线,再输出最终报告:
# 1. agent_config
# 2. timeout 的默认读取结果;
# 3. contains_model
# 4. contains_timeout
# 5. model_value_is_key
# 6. removed_retries
# 7. nested_config
# 8. agents
# 9. agent_profile
# 10. backup_config。
# 预期核心结果:
# 初次 get("timeout", 30) 得到 30但不会自动新增键
# 修改后的 temperature 为 0.3
# 修改后的 max_tokens 为 4000
# contains_model = True
# 添加 timeout 后 contains_timeout = True
# model_value_is_key = False
# removed_retries = 3
# timeout 最终被删除;
# 嵌套模型名称为 gpt-5超时时间为 30
# agent_profile 的 tools 包含“写作”;
# backup_config 的模型为 o3但 agent_config 的模型仍为 gpt-5。
# 完成后进行自查:
# 1. 方括号和 get() 是否按要求分别使用;
# 2. get() 默认值是否没有自动写入字典;
# 3. in 是否用于检查键;
# 4. 删除键时是否进行了安全处理;
# 5. items() 是否正确解包为 key 和 value
# 6. 嵌套字典是否使用两层键读取;
# 7. 列表中的每个 Agent 是否使用字典表达;
# 8. 修改 backup_config 是否没有影响 agent_config。