جواب «Step 4: Reading Level» چالش 4 از جلسهی 18
سؤال
دو تابع دیگر اضافه کن: count_sentences(text) — تعداد تکههای غیرخالی پس از جدا کردن متن با .، ! و ? (دستکم 1)، و reading_level(words_per_sentence, avg_word_length) که easy برگرداند اگر اولی <= 10 و دومی <= 4.5 باشد، hard اگر اولی > 20 یا دومی > 6 باشد، وگرنه medium. در انتهای خروجی مرحلهی ۳ اضافه کن:
````
Sentences: 3
Avg sentence length: 3.00
Avg word length: 3.11
Level: easy
راهنما
قبل از split، علامتهای ! و ? را با replace به . تبدیل کن. میانگین طول واژه = مجموع طولها تقسیم بر تعداد واژهها.
یک جواب درست
PUNCTUATION = ".,!?;:\"'()"
def tokenize(text):
words = (w.strip(PUNCTUATION) for w in text.lower().split())
return [w for w in words if w]
def word_frequency(words):
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
def top_words(freq, n=3):
return sorted(freq.items(), key=lambda item: (-item[1], item[0]))[:n]
def longest_words(words, n=3):
return sorted(set(words), key=lambda w: (-len(w), w))[:n]
def count_sentences(text):
parts = text.replace("!", ".").replace("?", ".").split(".")
return max(1, sum(1 for p in parts if p.strip()))
def reading_level(words_per_sentence, avg_word_length):
if words_per_sentence <= 10 and avg_word_length <= 4.5:
return "easy"
if words_per_sentence > 20 or avg_word_length > 6:
return "hard"
return "medium"
text = input()
words = tokenize(text)
print(f"Words: {len(words)}")
print(f"Unique: {len(set(words))}")
print("Top words:")
for word, count in top_words(word_frequency(words)):
print(f" {word}: {count}")
print(f"Longest: {', '.join(longest_words(words))}")
sentences = count_sentences(text)
per_sentence = len(words) / sentences
avg_length = sum(len(w) for w in words) / len(words)
print(f"Sentences: {sentences}")
print(f"Avg sentence length: {per_sentence:.2f}")
print(f"Avg word length: {avg_length:.2f}")
print(f"Level: {reading_level(per_sentence, avg_length)}")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن