جواب «Track A: Route to the Right Tool» چالش 4 از جلسهی 78
سؤال
مسیر الف. تابع route(question) را بنویس: اگر سؤال رقم دارد و یکی از عملگرهای + - * / به شکل یک کلمهی جدا در آن هست، calc برگرداند، وگرنه notes. بعد bot(question): برای calc عبارت a op b را از کلمههای سؤال بساز و calc امن را صدا بزن (= <result>)، برای notes همان answer آماده. خروجی:calc | = 4.5notes | Evaporation is when the sun heats water and it turns into vapour. [source: chunk 0]notes | Not in the notes.calc | = error: division by zero
راهنما
words = question.replace("?", " ").split()؛ has_digit = any(ch.isdigit() for ch in question)؛ has_op = any(w in OPS for w in words). برای عبارت: [w for w in words if w in OPS or w.replace(".", "").isdigit()] و " ".join(...).
یک جواب درست
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b, "/": lambda a, b: a / b}
NOTES = {"evaporation": "Evaporation is when the sun heats water and it turns into vapour. [source: chunk 0]"}
def calc(expr):
parts = expr.split()
if len(parts) != 3 or parts[1] not in OPS:
return "error: use a op b"
try:
a, b = float(parts[0]), float(parts[2])
except ValueError:
return "error: not a number"
if parts[1] == "/" and b == 0:
return "error: division by zero"
return OPS[parts[1]](a, b)
def answer(question):
for topic, text in NOTES.items():
if topic in question.lower():
return text
return "Not in the notes."
def route(question):
words = question.replace("?", " ").split()
has_digit = any(ch.isdigit() for ch in question)
has_op = any(w in OPS for w in words)
return "calc" if has_digit and has_op else "notes"
def bot(question):
if route(question) == "calc":
words = question.replace("?", " ").split()
expr = " ".join(w for w in words if w in OPS or w.replace(".", "").isdigit())
return "= " + str(calc(expr))
return answer(question)
for q in ["What is 18 / 4 ?", "What is evaporation?", "Is 7 a lucky number?", "What is 5 / 0 ?"]:
print(route(q), "|", bot(q))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن