Bird
0
0

The following code tries to handle negation but gives wrong sentiment scores:

medium📝 Debug Q14 of 15
NLP - Sentiment Analysis Advanced
The following code tries to handle negation but gives wrong sentiment scores:
sentence = "I am not happy"
words = sentence.split()
sentiment_dict = {"happy": 1}
score = 0
negate = False
for w in words:
    if w == "not":
        negate = True
    val = sentiment_dict.get(w, 0)
    if negate:
        val = -val
    score += val
print(score)

What is the main bug causing incorrect output?
ANegation flag is never reset after use
BSentiment dictionary missing 'not' key
CLoop skips words after 'not'
DScore is not initialized to zero
Step-by-Step Solution
Solution:
  1. Step 1: Analyze negation flag usage

    Negate is set True on 'not' but never reset to False, so all following words are negated.
  2. Step 2: Understand impact on sentiment score

    All words after 'not' get negated, causing wrong total sentiment.
  3. Final Answer:

    Negation flag is never reset after use -> Option A
  4. Quick Check:

    Negate flag reset missing = C [OK]
Quick Trick: Reset negation flag after negating one word [OK]
Common Mistakes:
MISTAKES
  • Forgetting to reset negation flag
  • Adding keys unnecessarily to sentiment dict
  • Assuming loop skips words after negation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NLP Quizzes