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

جواب «The Best Parts» چالش 4 از جلسه‌ی 42

سؤال

top_chunks(question, chunks, k) شماره‌ی (اندیس) حداکثر k تکه‌ی بهتر را برگرداند. k بار: از تکه‌هایی که هنوز انتخاب نشده‌اند، اولین تکه با بیشترین امتیاز را پیدا کن؛ فقط اگر امتیازش از 0 بیشتر بود اضافه‌اش کن، وگرنه دست نگه دار. خروجی test:
[0, 2]
[2]
[3]
[]

راهنما

در هر دور best = None و best_score = 0. با if i not in picked and s > best_score: جلو برو. اگر بعد از حلقه best هنوز None بود، break.

یک جواب درست

HANDOUT = """Nilu is a small made-up planet with two moons, Pip and Tov.
A day on Nilu lasts 30 hours, and a year lasts 200 days.

The glow trees of Nilu shine blue at night. They drink rain water
and grow 2 meters every year.

The sand foxes of Nilu sleep in the day and hunt at night.
They eat glow berries and small beetles.

Pip is the bigger moon. It turns around Nilu in 12 days.
Tov is tiny and turns around Nilu in 5 days."""

STOP = {"the", "a", "an", "is", "of", "in", "on", "and", "what", "how", "do", "does", "it", "at", "to", "many"}

def words(text):
    clean = ""
    for ch in text.lower():
        if ch in ".,?!":
            clean += " "
        else:
            clean += ch
    result = set()
    for w in clean.split():
        if w not in STOP:
            result.add(w)
    return result

def split_chunks(text):
    chunks = []
    for part in text.split("\n\n"):
        part = part.strip()
        if part != "":
            chunks.append(part)
    return chunks

def score(question, chunk):
    return len(words(question) & words(chunk))

def top_chunks(question, chunks, k):
    picked = []
    for round_number in range(k):
        best = None
        best_score = 0
        for i in range(len(chunks)):
            s = score(question, chunks[i])
            if i not in picked and s > best_score:
                best = i
                best_score = s
        if best is None:
            break
        picked.append(best)
    return picked


# ---- test with a pretend model (do not change) ----
chunks = split_chunks(HANDOUT)
print(top_chunks("How long is a day on Nilu?", chunks, 2))
print(top_chunks("What do sand foxes eat?", chunks, 2))
print(top_chunks("Which moon is bigger, Pip or Tov?", chunks, 1))
print(top_chunks("What is the capital of France?", chunks, 2))

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