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

جواب «One Step» چالش 3 از جلسه‌ی 73

سؤال

تابع step(decision) را بنویس که یک تصمیم (دیکشنری) را اجرا کند: اگر final داشت ("final", متن) برگرداند؛ اگر action در TOOLS نبود ("obs", "error: unknown tool <action>")؛ وگرنه ("obs", TOOLS[action](input)). خروجی:
obs 6779
obs 5963
obs error: unknown tool search_web
final Earth is bigger by 5963 km.

راهنما

if "final" in decision: return ("final", decision["final"])؛ name = decision["action"]؛ if name not in TOOLS: return ("obs", "error: unknown tool " + name)؛ return ("obs", TOOLS[name](decision["input"])).

یک جواب درست

DIAMETER_KM = {"mercury": 4879, "mars": 6779, "earth": 12742, "jupiter": 139820}


def lookup(name):
    return str(DIAMETER_KM.get(name.strip().lower(), "not found"))


def calc(expr):
    a, op, b = expr.split()
    a, b = int(a), int(b)
    return str({"+": a + b, "-": a - b, "*": a * b}[op])


TOOLS = {"lookup": lookup, "calc": calc}


def step(decision):
    if "final" in decision:
        return ("final", decision["final"])
    name = decision["action"]
    if name not in TOOLS:
        return ("obs", "error: unknown tool " + name)
    return ("obs", TOOLS[name](decision["input"]))


decisions = [
    {"thought": "I need Mars.", "action": "lookup", "input": "Mars"},
    {"thought": "Subtract.", "action": "calc", "input": "12742 - 6779"},
    {"thought": "Search the web?", "action": "search_web", "input": "planets"},
    {"thought": "Done.", "final": "Earth is bigger by 5963 km."},
]
for d in decisions:
    kind, text = step(d)
    print(kind, text)

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن