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

جواب «A Token Counter» چالش 3 از جلسه‌ی 37

سؤال

یک شمارنده‌ی توکن تقریبی بساز. count_tokens(text) برای هر کلمه (با split()):
- علامت‌های ,.?! را از دو سرش بردار (strip(",.?!"))؛ اگر چیزی ماند و بیشتر از ۶ حرف بود 2 توکن، وگرنه 1 توکن.
- هر علامت , . ? ! داخل کلمه‌ی اصلی هم 1 توکن.
خروجی test:
4
6
6

راهنما

clean = word.strip(",.?!")، بعد if len(clean) > 6: و elif len(clean) > 0:. برای علامت‌ها یک حلقه‌ی دوم: for ch in word: if ch in ",.?!": total += 1.

یک جواب درست

def count_tokens(text):
    total = 0
    for word in text.split():
        clean = word.strip(",.?!")
        if len(clean) > 6:
            total += 2
        elif len(clean) > 0:
            total += 1
        for ch in word:
            if ch in ",.?!":
                total += 1
    return total


# ---- test (do not change) ----
print(count_tokens("Hello, world!"))
print(count_tokens("Tell me about dinosaurs."))
print(count_tokens("Why is the sky blue?"))

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