How Similar? چالش 4 از جلسهی 71، متوسط
تابع jaccard(a, b) را بنویس: هر دو را set کن؛ اگر یکی خالی بود 0؛ وگرنه len(a & b) / len(a | b). برنامه شباهت سؤال Why does rain fall from clouds? را با هر چهار تکه، با دو رقم اعشار، چاپ میکند. خروجی:chunk 0: 0.00chunk 1: 0.10chunk 2: 0.20chunk 3: 0.00
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):
return 0
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.",
]
q = tokens("Why does rain fall from clouds?")
for i, chunk in enumerate(CHUNKS):
print(f"chunk {i}: {jaccard(q, tokens(chunk)):.2f}")
راهنما و جواب این چالش · برگشت به درس جلسهی 71: RAG کوچک (۱): تکهی درست را پیدا کن · چالش بعدی: The Best Chunk, or None
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال