The problem
Build a priority queue of named tasks (lesson 4). A smaller priority number means more urgent.
add(task, priority): add a task. If the task is already waiting, change its priority instead; this counts as a new arrival.remove(task): take a waiting task out. ReturnTrue, orFalseif it was not waiting.pop(): remove and return the waiting task with the smallest priority. If several tasks share that priority, return the one that arrived first. ReturnNoneif nothing is waiting.len(q): the number of waiting tasks.
q = TaskQueue()
q.add('write', 3); q.add('fix', 1); q.add('test', 3)
q.pop() # 'fix'
q.remove('write') # True
q.pop() # 'test'
q.pop() # None
Task names are strings; priorities are integers.
The heapq module is switched off for this problem: write the heap yourself. A heap is a plain list with sift up and sift down (lessons 1 and 2); you can copy your class from HEAP-P1.
Limits
- Up to 30,000 tasks and about 70,000 operations; each should take O(log n) time.
Builds on HEAP-4 heapq and priority queues.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
7 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Lowest priority first | Not run | |
| 2 | Ties: first come, first served | Not run | |
| 3 | Remove | Not run | |
| 4 | Change a priority | Not run | |
| 5 | Changed task goes to the back of its tie | Not run | |
| 6 | Remove, then add back | Not run | |
| 7 | 30,000 tasks | Not run |