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"]
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"]