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))- A. False False False 1 True
- B. True False True 1 True
- C. True True False 1 True
- 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
- What is printed? python def f(x): try: r = 10 / x except ZeroDivisionError: r = "inf" return r else: r = round(r) finally: r = str(r) +…
- What is printed? python class A: def eq(self, o): print("A", end=" ") return NotImplemented class B: def eq(self, o): print("B", end=" ")…
- What is printed? python class N: def add(self, o): return "N.add" def radd(self, o): return "N.radd" class S(N): def radd(self, o): return…
- What is printed? python class C: k = 5 def f(self, v=k): return v def g(self): try: return k except NameError: return "NE" C.k = 9…
- What is printed? python d = {"a": 1} print(d.get("b", 0), "a" in d, 1 in d, d.get("b"))
- What is printed? python print(list("ab") + ["c"], tuple([1, 2]) 2)