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
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):
return "notes"
def bot(question):
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))
راهنما و جواب این چالش · برگشت به درس جلسهی 78: پروژهی آزاد با مربی (۲): ساختن · چالش بعدی: Track B: Centroid or k-NN?
بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال