ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class P:
def __init__(self, x, y): self.x, self.y = x, y
def __eq__(self, o): return self.x == o.x
def __hash__(self): return hash(self.x)
def __repr__(self): return f"P({self.x},{self.y})"
s = {P(1, "a"), P(2, "b")}
s.add(P(1, "c"))
d = {P(1, "a"): "first"}
d[P(1, "z")] = "second"
print(sorted(map(repr, s)), d, len({P(i % 2, i) for i in range(5)}))- A. ['P(1,c)', 'P(2,b)'] {P(1,z): 'second'} 2
- B. ['P(1,a)', 'P(1,c)', 'P(2,b)'] {P(1,a): 'first', P(1,z): 'second'} 5
- C. ['P(1,a)', 'P(2,b)'] {P(1,z): 'second'} 2
- D. ['P(1,a)', 'P(2,b)'] {P(1,a): 'second'} 2
Correct answer: D. ['P(1,a)', 'P(2,b)'] {P(1,a): 'second'} 2
Sets and dicts decide 'same key' by hash plus ==, and here both look only at x. Adding an equal element to a set is a no-op – the ORIGINAL object P(1,a) stays. Assigning through an equal key to a dict replaces the value but also keeps the ORIGINAL key object, so the dict shows P(1,a): 'second'. The comprehension has only x = 0 and x = 1, so 2 elements. Options showing P(1,c) or P(1,z) assume the newer object replaces the stored one.
More Python Programming questions
- What is printed? python it = iter(range(10)) a = list(zip(it, "ab")) b = next(it) c = [x for x in it if next(it, 0) % 3] print(a, b, c)
- What is printed? python def tag(t): print("make", t, end=" ") def deco(fn): print("wrap", t, end=" ") def inner(a): return f"<{t}>" +…
- What is printed? python x = 1 class K: x = 2 a = [x for in range(2)] b = [x i for i in range(x + 1)] def m(self): return x print(K.a, K.b…
- What is printed? python data = [5, 3, 8, 1] out = [] while (n := len(data)) > 1: first, data = data data[-1] += first out.append((n…
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def path(n): return [0] if n == 0 else path(n - 1) + [n] p…
- What is printed? python class Seq: def init(self, n): self.n = n; self.calls = 0 def getitem(self, i): self.calls += 1 if i >= self.n…