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

Nearest Sentence چالش 6 از جلسه‌ی 33، سخت

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

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):
    pass


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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 33: متن برای کامپیوتر

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال