جواب «The Best Chunk, or None» چالش 5 از جلسهی 71
سؤال
تابع best_chunk(question, chunks) را بنویس که (index, score) بهترین تکه را برگرداند؛ اگر بیشترین امتیاز 0 بود، (None, 0). برنامه برای هر سؤال، شماره و امتیاز تکه یا no match چاپ میکند. خروجی:What is evaporation? -> chunk 0 (0.10)Why does rain fall from clouds? -> chunk 2 (0.20)How do clouds form? -> chunk 1 (0.12)Who won the football match? -> no match
راهنما
best, best_score = None, 0؛ q = tokens(question)؛ for i, chunk in enumerate(chunks): s = jaccard(q, tokens(chunk)); if s > best_score: best, best_score = i, s.
یک جواب درست
STOP = {"the", "a", "an", "is", "are", "and", "or", "of", "in", "on", "to", "into", "it", "this",
"that", "what", "how", "why", "does", "do", "as", "when", "they", "called", "its"}
def tokens(text):
words = []
for w in text.lower().split():
w = "".join(ch for ch in w if ch.isalpha())
if w and w not in STOP:
words.append(w)
return words
def jaccard(a, b):
a, b = set(a), set(b)
if not a or not b:
return 0
return len(a & b) / len(a | b)
CHUNKS = [
"The sun heats water in seas and lakes. The warm water turns into vapour and rises. This is called evaporation.",
"High in the sky the vapour cools and forms clouds. This is called condensation.",
"When the drops in a cloud get heavy, they fall as rain or snow. This is called precipitation.",
"Plants take in water through their roots and lose it through their leaves.",
]
def best_chunk(question, chunks):
q = tokens(question)
best, best_score = None, 0
for i, chunk in enumerate(chunks):
s = jaccard(q, tokens(chunk))
if s > best_score:
best, best_score = i, s
return best, best_score
for q in ["What is evaporation?", "Why does rain fall from clouds?", "How do clouds form?", "Who won the football match?"]:
index, score = best_chunk(q, CHUNKS)
if index is None:
print(q, "-> no match")
else:
print(f"{q} -> chunk {index} ({score:.2f})")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن