HEAP-P3

A task queue

Practice 3 of 6Heaps7 tests

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. Return True, or False if 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. Return None if 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

7 tests, not run yet
Test results
#TestResultReads · time
1Lowest priority firstNot run
2Ties: first come, first servedNot run
3RemoveNot run
4Change a priorityNot run
5Changed task goes to the back of its tieNot run
6Remove, then add backNot run
730,000 tasksNot run