جواب «Words and Scores» چالش 3 از جلسهی 42
سؤال
words(text) مجموعهی کلمهها را برگرداند: متن را lower() کن، هر کدام از .,?! را فاصله کن، با split() بشکن و کلمههایی را که در STOP نیستند به یک set اضافه کن. score(question, chunk) تعداد کلمههای مشترک است: len(words(question) & words(chunk)). خروجی test:['day', 'long', 'nilu']['foxes', 'nilu', 'sand']1141
راهنما
حرف به حرف بساز: for ch in text.lower(): if ch in ".,?!": clean += " " وگرنه clean += ch.
یک جواب درست
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 score(question, chunk):
return len(words(question) & words(chunk))
# ---- test (do not change) ----
print(sorted(words("How long is a day on Nilu?")))
print(sorted(words("The sand foxes, of Nilu!")))
chunks = HANDOUT.split("\n\n")
for chunk in chunks:
print(score("What do the sand foxes of Nilu eat?", chunk))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن