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)])
  1. A. [3, 1, 2]
  2. B. [2, 1, 3]
  3. C. [1, 3, 2]
  4. 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

Exams that ask this topic