بتل کد Battle Codeدارد باز می‌شود…

جواب «How Similar?» چالش 4 از جلسه‌ی 71

سؤال

تابع jaccard(a, b) را بنویس: هر دو را set کن؛ اگر یکی خالی بود 0؛ وگرنه len(a & b) / len(a | b). برنامه شباهت سؤال Why does rain fall from clouds? را با هر چهار تکه، با دو رقم اعشار، چاپ می‌کند. خروجی:
chunk 0: 0.00
chunk 1: 0.10
chunk 2: 0.20
chunk 3: 0.00

راهنما

a, b = set(a), set(b)؛ if not a or not b: return 0؛ return len(a & b) / len(a | b).

یک جواب درست

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.",
]
q = tokens("Why does rain fall from clouds?")
for i, chunk in enumerate(CHUNKS):
    print(f"chunk {i}: {jaccard(q, tokens(chunk)):.2f}")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن