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

جواب «Step 2: Maybe Unkind, and Why» چالش 2 از جلسه‌ی 36

سؤال

قدم ۲. تابع check(text) بنویس که دو چیز برگرداند: score (جمع وزن کلمه‌ها با weights.get(word, 0)) و لیست bad_words (کلمه‌هایی که وزنشان منفی است). بعد برای سه نظر نمونه: اگر score < 0 بود چاپ کن boring and so slow -> maybe unkind because of: boring, slow، وگرنه what a fun level -> ok.

راهنما

def check(text): با score = 0 و bad_words = []؛ برای هر کلمه w = weights.get(word, 0)، score += w و if w < 0: bad_words.append(word). آخر return score, bad_words.

یک جواب درست

TRAIN = [
    ("great game i love it", "kind"), ("so fun and so cool", "kind"), ("nice colors", "kind"),
    ("amazing work", "kind"), ("i love the music", "kind"), ("this is so cool", "kind"),
    ("great idea", "kind"), ("fun level and nice music", "kind"), ("thanks for sharing", "kind"),
    ("cool game well done", "kind"), ("the art is beautiful", "kind"), ("so funny i love it", "kind"),
    ("well done great job", "kind"), ("nice and fun", "kind"), ("the best game ever", "kind"),
    ("i like the colors", "kind"), ("beautiful work thanks", "kind"), ("very cool idea", "kind"),
    ("fun fun fun", "kind"), ("good job", "kind"),
    ("this is boring", "unkind"), ("so stupid", "unkind"), ("worst game ever", "unkind"),
    ("ugly colors", "unkind"), ("i hate it", "unkind"), ("boring and slow", "unkind"),
    ("lame idea", "unkind"), ("this is dumb", "unkind"), ("you are a loser", "unkind"),
    ("the music is awful", "unkind"), ("so slow and boring", "unkind"), ("terrible game", "unkind"),
    ("ugly and stupid", "unkind"), ("i hate this game", "unkind"), ("worst idea", "unkind"),
    ("dumb level", "unkind"), ("boring music", "unkind"), ("awful art", "unkind"),
    ("this game is lame", "unkind"), ("so bad", "unkind"),
]

TEST = [
    ("i love the art", "kind"), ("boring level", "unkind"), ("cool music", "kind"),
    ("this is the worst", "unkind"), ("so nice", "kind"), ("ugly game", "unkind"),
    ("not bad at all", "kind"), ("you are not funny", "unkind"), ("great work", "kind"),
    ("slow and lame", "unkind"),
]

weights = {}
for text, label in TRAIN:
    for word in text.split():
        if word not in weights:
            weights[word] = 0
        if label == "kind":
            weights[word] += 1
        else:
            weights[word] -= 1

for word in ["love", "boring", "game", "the", "fun"]:
    print(word, weights.get(word, 0))

def check(text):
    score = 0
    bad_words = []
    for word in text.split():
        w = weights.get(word, 0)
        score += w
        if w < 0:
            bad_words.append(word)
    return score, bad_words

for text in ["what a fun level", "boring and so slow", "i like the game"]:
    score, bad_words = check(text)
    if score < 0:
        print(text, "-> maybe unkind because of:", ", ".join(bad_words))
    else:
        print(text, "-> ok")

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