جواب «Check the Plan First» چالش 2 از جلسهی 74
سؤال
تابع check_plan(plan) را بنویس که لیست مشکلها را برگرداند: اگر تعداد قدمها بیشتر از MAX_STEPS است too many steps (<n> > <MAX_STEPS>)؛ و برای هر قدم (شماره از ۱) که ابزارش در TOOLS نیست step <i>: unknown tool <tool>. خروجی:plan A: okplan B: step 2: unknown tool hack_wifiplan C: too many steps (5 > 4)plan D: ok
راهنما
if len(plan) > MAX_STEPS: problems.append(f"too many steps ({len(plan)} > {MAX_STEPS})")؛ for i, step in enumerate(plan, 1): if step["tool"] not in TOOLS: ....
یک جواب درست
MAX_STEPS = 4
TOOLS = {"lookup", "calc", "make_quiz", "send_message"} # only the names matter here
def check_plan(plan):
problems = []
if len(plan) > MAX_STEPS:
problems.append(f"too many steps ({len(plan)} > {MAX_STEPS})")
for i, step in enumerate(plan, 1):
if step["tool"] not in TOOLS:
problems.append(f"step {i}: unknown tool {step['tool']}")
return problems
plans = {
"A": [{"tool": "lookup", "input": "Mars"}, {"tool": "lookup", "input": "Earth"}, {"tool": "calc", "input": "{2} - {1}"}],
"B": [{"tool": "lookup", "input": "school"}, {"tool": "hack_wifi", "input": "neighbour"}],
"C": [{"tool": "lookup", "input": str(i)} for i in range(5)],
"D": [{"tool": "lookup", "input": "Mars"}, {"tool": "lookup", "input": "Earth"},
{"tool": "calc", "input": "{2} - {1}"}, {"tool": "make_quiz", "input": "planets"}],
}
for name, plan in plans.items():
problems = check_plan(plan)
print(f"plan {name}:", "; ".join(problems) if problems else "ok")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن