ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
import heapq
pts = [(1, 3), (-2, 2), (2, -2), (0, 1)]
print(heapq.nsmallest(2, pts, key=lambda p: p[0] ** 2 + p[1] ** 2))
  1. A. [(0, 1), (-2, 2)]
  2. B. [(0, 1), (5, 2)]
  3. C. [(0, 1), (1, 3)]
  4. D. [(-2, 2), (2, -2)]

Correct answer: A. [(0, 1), (-2, 2)]

Squared distances are 10, 8, 8 and 1. nsmallest keeps equal keys in input order, so (-2, 2) comes before (2, -2) for the second slot.

More Python Programming questions

Exams that ask this topic