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

جواب «Nearest Sentence» چالش 6 از جلسه‌ی 33

سؤال

با کیسه‌ی کلمات و k-NN نزدیک‌ترین جمله را پیدا کن. تابع most_similar(query, sentences, vocab) بنویس که کیسه‌ی query را با کیسه‌ی هر جمله مقایسه کند (فاصله‌ی اقلیدسی) و نزدیک‌ترین جمله را برگرداند. برنامه برای دو پرسش چاپ می‌کند: the cat sat on the mat و my dog runs fast.

راهنما

q = bag(query, vocab)؛ برای هر جمله d = distance(q, bag(s, vocab)) و بهترین را نگه دار.

یک جواب درست

import math


def tokens(text):
    clean = "".join(ch for ch in text.lower() if ch.isalpha() or ch == " ")
    return clean.split()


def bag(sentence, vocab):
    counts = [0] * len(vocab)
    for word in tokens(sentence):
        if word in vocab:
            counts[vocab.index(word)] += 1
    return counts


def distance(a, b):
    return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(len(a))))


sentences = ["the cat sat on the mat", "my dog runs fast", "a bird sings in the tree"]
vocab = sorted(set(w for s in sentences for w in tokens(s)))


def most_similar(query, sentences, vocab):
    q = bag(query, vocab)
    best = None
    best_d = None
    for s in sentences:
        d = distance(q, bag(s, vocab))
        if best_d is None or d < best_d:
            best_d = d
            best = s
    return best


print(most_similar("a cat on a mat", sentences, vocab))
print(most_similar("the dog is fast!", sentences, vocab))

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