جواب «Step 1: Find the Part» چالش 1 از جلسهی 44
سؤال
جزوه، words، split_chunks و score آمادهاند و CHUNKS تکههای جزوه است. best_chunk(question) اندیس تکهای با بیشترین امتیاز را برگرداند (اگر دو تا برابر بودند، اولی)؛ اگر هیچ تکهای امتیاز بیشتر از 0 نگرفت، None. خروجی test: 0، 1، 2، 3، None.
راهنما
best = None و best_score = 0؛ برای هر i اگر s > best_score بود هر دو را عوض کن.
یک جواب درست
HANDOUT = """The Robo Garden club meets every Tuesday after school.
The club has 12 members and one teacher.
The garden has 4 tomato beds and 2 herb beds.
Each tomato bed needs 3 liters of water every day.
The robot Sprout waters the beds at 7 in the morning.
Sprout runs on a small solar panel.
Ripe tomatoes are picked on Fridays.
Herbs are picked whenever the cook asks for them."""
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))
CHUNKS = split_chunks(HANDOUT)
def best_chunk(question):
best = None
best_score = 0
for i in range(len(CHUNKS)):
s = score(question, CHUNKS[i])
if s > best_score:
best = i
best_score = s
return best
# ---- test (do not change) ----
for q in ["When does the club meet?", "How much water does a tomato bed need?",
"Who waters the beds?", "When are tomatoes picked?", "What is the capital of France?"]:
print(best_chunk(q))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن