ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class K:
    def __init__(self, v): self.v = v
    def __hash__(self): return hash(self.v)
    def __eq__(self, o): return self.v == o.v

k = K(1)
s = {k}
k.v = 2
print(k in s, K(1) in s, K(2) in s, len(s), any(e is k for e in s))
  1. A. False False False 1 True
  2. B. True False True 1 True
  3. C. True True False 1 True
  4. D. False True False 1 True

Correct answer: A. False False False 1 True

A set files an element under the hash it had when inserted (hash(1)). After k.v = 2, looking up k or K(2) computes hash(2) and searches a different slot, so neither is found. K(1) has the right hash, but the stored object now has v = 2, so __eq__ says unequal. The object is still physically inside the set (iteration finds it), which is why mutating fields used by __hash__ silently breaks sets and dicts.

More Python Programming questions

Exams that ask this topic