Back
+20 XP
Concept

Finding Top-K Elements with nsmallest & nlargest

`heapq.nlargest(k, iterable)` and `heapq.nsmallest(k, iterable)` find top-$K$ elements in $O(n \log k)$ time, vastly outperforming full sorting ($O(n \log n)$) when $k \ll n$ 🏆.

python
import heapq

scores = [12, 95, 34, 88, 45, 99, 23, 76]

top_3 = heapq.nlargest(3, scores)
bottom_2 = heapq.nsmallest(2, scores)

print(f"Top 3: {top_3} 🏆")      # [99, 95, 88]
print(f"Bottom 2: {bottom_2} 📉") # [12, 23]

# 6. Finding Top-K Elements with nsmallest & nlargest `heapq.nlargest(k, iterable)` and `heapq.nsmallest(k, iterable)` find top-$K$ elements in $O(n \log k)$ time, vastly outperforming full sorting ($O(n \log n)$) when $k \ll n$ 🏆. ```python import heapq scores = [12, 95, 34, 88, 45, 99, 23, 76] top_3 = heapq.nlargest(3, scores) bottom_2 = heapq.nsmallest(2, scores) print(f"Top 3: {top_3} 🏆") # [99, 95, 88] print(f"Bottom 2: {bottom_2} 📉") # [12, 23] ``` When building search leaderboards or filtering metrics, never sort the entire collection if you only need the top 5 results! 🏆 --- ### Question Why is `heapq.nlargest(5, million_items)` much faster than `sorted(million_items)[-5:]`? 🧠 - [ ] a. It maintains a tiny 5-element heap in memory ($O(n \log k)$) instead of sorting all 1,000,000 items 🏆 - [ ] b. It uses multi-core threading automatically - [ ] c. It converts all integers into strings - [ ] d. It only reads the first 100 items --- ### Challenge Import `heapq`. Given `data = [42, 10, 99, 8, 77, 23]`, use `heapq.nlargest(2, data)` and print the resulting list. 🎯 <details> <summary>Solution</summary> ```python import heapq data = [42, 10, 99, 8, 77, 23] top_2 = heapq.nlargest(2, data) print(top_2) ``` </details>

Checkpoint

Why is `heapq.nlargest(5, million_items)` much faster than `sorted(million_items)[-5:]`? 🧠

Practice

Import `heapq`. Given `data = [42, 10, 99, 8, 77, 23]`, use `heapq.nlargest(2, data)` and print the resulting list. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks