بتل کد 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.

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):
    return ("obs", "")


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)

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 73: عامل: فکر، عمل، مشاهده · چالش بعدی: The Agent Loop with a Trace

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