جواب «Stop Safely and Report» چالش 5 از جلسهی 74
سؤال
تابع run_plan(plan) را بنویس که قدمها را با fill اجرا کند و در این حالتها بایستد و پیام برگرداند: ۱) نتیجهی ابزار با error شروع شد: stopped at step <i>: <result>؛ ۲) ابزار در NEEDS_OK است و human_ok(input) جواب False داد: stopped at step <i>: a human said no. اگر همهی قدمها اجرا شد: done: <n> steps, last result: <result>. خروجی:done: 2 steps, last result: sent to teacherstopped at step 1: error: no data for plutostopped at step 2: a human said no
راهنما
ترتیب در هر قدم: پر کن → اگر step["tool"] in NEEDS_OK and not human_ok(text) بایست → اجرا کن → اگر result.startswith("error") بایست → results.append(result). آخر: return f"done: {len(results)} steps, last result: {results[-1]}".
یک جواب درست
DIAMETER_KM = {"mars": 6779, "earth": 12742}
def lookup(name):
if name.lower() not in DIAMETER_KM:
return "error: no data for " + name.lower()
return str(DIAMETER_KM[name.lower()])
def send_message(text):
to = text.split(":")[0]
return "sent to " + to # pretend: nothing is really sent
TOOLS = {"lookup": lookup, "send_message": send_message}
NEEDS_OK = {"send_message"}
def human_ok(text):
# A pretend human: agrees to messages for the teacher only.
return text.startswith("teacher:")
def fill(text, results):
for i, r in enumerate(results, 1):
text = text.replace("{" + str(i) + "}", r)
return text
def run_plan(plan):
results = []
for i, step in enumerate(plan, 1):
text = fill(step["input"], results)
if step["tool"] in NEEDS_OK and not human_ok(text):
return f"stopped at step {i}: a human said no"
result = TOOLS[step["tool"]](text)
if result.startswith("error"):
return f"stopped at step {i}: {result}"
results.append(result)
return f"done: {len(results)} steps, last result: {results[-1]}"
plans = [
[{"tool": "lookup", "input": "Earth"}, {"tool": "send_message", "input": "teacher: Earth is {1} km wide."}],
[{"tool": "lookup", "input": "Pluto"}, {"tool": "send_message", "input": "teacher: Pluto is {1} km wide."}],
[{"tool": "lookup", "input": "Mars"}, {"tool": "send_message", "input": "everyone: Mars is {1} km wide!"}],
]
for plan in plans:
print(run_plan(plan))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن