ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
class Money:
    def __init__(self, v): self.v = v
    def __lt__(self, o): return self.v < o.v
    def __repr__(self): return f"M{self.v}"
xs = [Money(3), Money(1), Money(2)]
print(sorted(xs), max(xs), Money(1) > Money(0))
  1. A. [M1, M2, M3] M3 TypeError
  2. B. [M3, M1, M2] M3 True
  3. C. TypeError
  4. D. [M1, M2, M3] M3 True

Correct answer: D. [M1, M2, M3] M3 True

sorted and max only need __lt__. For a > b Python tries a.__gt__ (missing, returns NotImplemented) and then the reflected b.__lt__(a), which is 0 < 1 = True.

More Python Programming questions

Exams that ask this topic