5 of 6
You're building a task scheduler for a game server. Tasks arrive with a priority number — the lower the number, the more urgent the task.
Your job: process all tasks in priority order!
Write a function process_tasks(tasks) that:
(priority, task_name) tuplesUse heapq!
tasks = [(3, "Email"), (1, "Fire"), (2, "Meeting"), (1, "Crash")] print(process_tasks(tasks)) # Output: ["Crash", "Fire", "Meeting", "Email"] # (or ["Fire", "Crash", ...] — both priority-1 tasks can go first) tasks2 = [(5, "Cleanup"), (1, "Critical Bug"), (3, "Feature")] print(process_tasks(tasks2)) # Output: ["Critical Bug", "Feature", "Cleanup"]
import heapq def process_tasks(tasks): # Your code here pass # Test your function: tasks = [(3, "Email"), (1, "Fire"), (2, "Meeting"), (1, "Crash")] print(process_tasks(tasks)) # Output: ["Crash", "Fire", "Meeting", "Email"] tasks2 = [(5, "Cleanup"), (1, "Critical Bug"), (3, "Feature")] print(process_tasks(tasks2)) # Output: ["Critical Bug", "Feature", "Cleanup"]
When you push a tuple into a heap, Python compares by the first element (priority number). That's exactly what we want!
(priority, name) tuples into a heapimport heapq def process_tasks(tasks): heap = [] for priority, name in tasks: heapq.heappush(heap, (priority, name)) result = [] while heap: priority, name = heapq.heappop(heap) result.append(name) return result
Why this works: Tuples are compared element-by-element. Since priority is first, the heap sorts by priority automatically. Lower numbers = higher urgency = popped first!
What if you want higher priority numbers to go first? (e.g., priority 5 is more urgent than priority 1)
Modify your function to handle this. (Hint: negate trick again!)
tasks = [(3, "Email"), (5, "Fire"), (2, "Meeting")] print(process_tasks_max(tasks)) # Output: ["Fire", "Email", "Meeting"]
✅ Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
✅ Functions, classes, recursion, print()
❌ No file system, subprocess, OS access, or network requests
❌ No pip install (all supported modules are pre-loaded)
⏱️ 5 second execution time limit