بتل کد Battle Codeدارد باز می‌شود…

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 teacher
stopped at step 1: error: no data for pluto
stopped at step 2: a human said no

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)
        results.append(TOOLS[step["tool"]](text))
    return "done"


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))

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 74: عامل چندابزاره · چالش بعدی: Put the Tools in Order

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال