Which Answer Wins? چالش 6 از جلسهی 63، سخت
داور خودکار آماده است. تابع compare(a, b) را بنویس که هر دو جواب را با score_answer(text, 40) نمره بدهد و یک جمله برگرداند: اگر a نمرهی بیشتری داشت first wins (4 vs 3)، اگر b بیشتر بود second wins (1 vs 3)، و اگر مساوی بود tie (3 vs 3): read both yourself. خروجی برای سه مقایسه باید این باشد:first wins (4 vs 3)second wins (1 vs 3)tie (3 vs 3): read both yourself
def verify(claim):
left, right = claim.split(" = ")
a, op, b = left.split()
a, b = int(a), int(b)
real = {"+": a + b, "-": a - b, "*": a * b}[op]
return real == int(right)
def score_answer(text, max_words):
lines = text.splitlines()
passed = []
if len([l for l in lines if l.startswith("Step")]) >= 2:
passed.append("steps")
if any(l.startswith("Answer:") for l in lines):
passed.append("answer")
if len(text.split()) <= max_words:
passed.append("length")
claims = [l.split(": ")[1] for l in lines if " = " in l]
if all(verify(c) for c in claims):
passed.append("maths")
return passed
def compare(a, b):
pass
A = "Step 1: 3 * 4 = 12\nStep 2: 2 * 1 = 2\nStep 3: 12 + 2 = 14\nAnswer: 14 dollars"
B = "Notebooks: 3 * 4 = 12\nPens: 2 * 1 = 3\nTotal: 12 + 3 = 15\nSo you pay 15 dollars for everything."
C = "Step 1: 3 * 4 = 12\nStep 2: 2 * 1 = 2\nStep 3: 12 + 2 = 16\nAnswer: 16 dollars"
D = "Step 1: 4 * 3 = 12\nStep 2: 1 * 2 = 2\nStep 3: 2 + 12 = 15\nAnswer: 15 dollars"
print(compare(A, C))
print(compare(B, C))
print(compare(C, D))
راهنما و جواب این چالش · برگشت به درس جلسهی 63: پرامپتنویسی پیشرفته ۲
بیشتر بخوان: list comprehension در پایتون: از حلقه for تا یک خط کد