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)}))
  1. A. ['P(1,c)', 'P(2,b)'] {P(1,z): 'second'} 2
  2. B. ['P(1,a)', 'P(1,c)', 'P(2,b)'] {P(1,a): 'first', P(1,z): 'second'} 5
  3. C. ['P(1,a)', 'P(2,b)'] {P(1,z): 'second'} 2
  4. 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

Exams that ask this topic