Bird
0
0

Find the bug in this code that calculates Jaccard similarity:

medium📝 Debug Q7 of 15
NLP - Text Similarity and Search
Find the bug in this code that calculates Jaccard similarity:
def jaccard_similarity(A, B):
    intersection = len(set(A) & set(B))
    union = len(set(A) | set(B))
    return intersection / len(union)

print(jaccard_similarity([1,2,3], [2,3,4]))
ANot converting lists to sets
BUsing len(union) instead of union variable
CReturning intersection instead of ratio
DUsing set intersection instead of union
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the union calculation

    union is an integer (length), but code uses len(union) which is invalid.
  2. Step 2: Identify the error

    len(union) causes TypeError because union is int, not a collection.
  3. Final Answer:

    Using len(union) instead of union variable -> Option B
  4. Quick Check:

    Use union directly, not len(union) [OK]
Quick Trick: Don't apply len() to an integer variable [OK]
Common Mistakes:
MISTAKES
  • Calling len() on an int
  • Mixing intersection and union sets
  • Forgetting to convert lists to sets

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NLP Quizzes