Keep the k largest values with a heap

Problem

Implement k_largest(xs, k) using heapq. Return the k largest values in descending order. For k <= 0, return []; if k exceeds the input length, return all values in descending order.

Starter code

def k_largest(xs, k):
    pass
Reveal answer or reference solution
import heapq
def k_largest(xs, k):
    if k <= 0:
        return []
    return sorted(heapq.nlargest(k, xs), reverse=True)

Public tests

  • k_largest([4,1,7,3,7], 3)[7, 7, 4]
  • k_largest([2,1], 5)[2, 1]
  • k_largest([2,1], 0)[]

Local history

Loading attempts saved in this browser…

Use with your agent

Share this URL and your attempt. Ask the agent to start with a clarifying question or the smallest useful hint.

Tutor me on https://mlprep.iwase.dev/programming/data-structures/original-py-heap/. If window.mlPrepAgent is available, read attempts for item original-py-heap before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record and read it back.

Appears in