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))- A. [M1, M2, M3] M3 TypeError
- B. [M3, M1, M2] M3 True
- C. TypeError
- 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
- What is printed? python class A: def eq(self, o): print("A.eq", end=" ") return NotImplemented class B(A): def eq(self, o): print("B.eq"…
- What is printed? python class Lazy: def init(self): self.calls = 0 @property def value(self): self.calls += 1 return 42 from functools…
- What is printed? python class Pos: def setname(self, owner, name): self.name = "" + name def get(self, obj, typ=None): return getattr(obj…
- What is printed? python def f(n): return [i for i in range(n) if i % 3 == 0 if i % 2 == 0] g = lambda n: [i for i in range(n) if i % 3 ==…
- What is printed? python a = {"x": 1, "y": 2} b = {v: k for k, v in a.items()} c = {k: v for k, v in zip("abc", [1, 2])} print(b, c, {1…
- What is printed? python a = b = [] a.append(1) c, d = [], [] c.append(1) x = y = 5 x += 1 print(b, d, y)