جواب «The Not Rule» چالش 5 از جلسهی 33
سؤال
قانون «نه» را اضافه کن: اگر کلمه not بود، flip = True و برو کلمهی بعد (continue). وگرنه w = WEIGHTS.get(word, 0)؛ اگر flip بود و w صفر نبود، w = -w و flip = False. بعد total += w. خروجی:1 this is not bad-2 not great at all5 i do not hate it it is fun-2 boring
راهنما
داخل حلقه: if word == "not": flip = True; continue. بعد w = ... و if flip and w != 0: w = -w; flip = False. خط total += WEIGHTS.get(...) را با total += w عوض کن.
یک جواب درست
WEIGHTS = {"great": 2, "fun": 2, "love": 2, "nice": 1, "cool": 1, "kind": 2,
"boring": -2, "bad": -1, "stupid": -3, "ugly": -2, "hate": -3, "slow": -1}
def score(sentence):
total = 0
flip = False
for word in sentence.split():
if word == "not":
flip = True
continue
w = WEIGHTS.get(word, 0)
if flip and w != 0:
w = -w
flip = False
total += w
return total
for s in ["this is not bad", "not great at all", "i do not hate it it is fun", "boring"]:
print(score(s), s)
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن