Standard library · 14 / 17 Exercise Medium

The k largest and smallest

Objective

The heapq module implements heaps (priority queues). With nlargest and nsmallest you get the extremes of a list without sorting it entirely.

Instructions

  • Read an integer k and a line with whole numbers (there are at least k).
  • Compute the k largest with heapq.nlargest(k, numbers): they come out from largest to smallest.
  • Compute the k smallest with heapq.nsmallest(k, numbers): they come out from smallest to largest.
  • Show Largest: ... and Smallest: ..., with the values separated by a space.
Input
2
5 1 9 3 7
Output
Largest: 9 7
Smallest: 1 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise