ProgrammingHardAccenture pattern
What is printed?
What is printed?
class W:
def __init__(self, x):
self.x = x
def __lt__(self, o):
return self.x < o.x
ws = [W(3), W(1), W(2)]
print([w.x for w in sorted(ws)])- A. [3, 1, 2]
- B. [2, 1, 3]
- C. [1, 3, 2]
- D. [1, 2, 3]
Correct answer: D. [1, 2, 3]
sorted() needs only __lt__ to compare and order objects; with it defined, the objects sort by x ascending, giving [1, 2, 3].
More Python Programming questions
- What is printed? python class N: def init(self, v): self.v = v def bool(self): return self.v != 0 n1 = N(0) n2 = N(5) print(bool(n1)…
- What is printed? python class Base: def repr(self): return "Base" class Sub(Base): pass print([Sub(), Sub()])
- What is printed? python class CM3: def enter(self): return 42 def exit(self, et, ev, tb): return False with CM3() as val: print(val)
- What is printed? python from contextlib import contextmanager @contextmanager def cm(): print("setup") yield 1 print("teardown") with cm()…
- What is printed? python class A: def enter(self): print("A enter"); return self def exit(self, a): print("A exit") class B: def…
- What is printed? python class A: def who(self): return "A" class B(A): def who(self): return "B" class C(A): def who(self): return "C"…