ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
print(heapq.nsmallest(3, [3, 1, 3, 2], key=lambda x: -x))
  1. A. [3, 2, 1]
  2. B. [3, 3, 1]
  3. C. [1, 2, 3]
  4. D. [3, 3, 2]

Correct answer: D. [3, 3, 2]

The keys are -3, -1, -3, -2. The three smallest keys are -3 (the first 3), -3 (the second 3) and -2 (the 2). nsmallest is equivalent to sorted(...)[:n] with the same key, so ties keep their original order.

More Python Programming questions

Exams that ask this topic