Debugging challengeIntermediate
The scheduler that ran the least urgent task
Scenario
A task scheduler is supposed to run tasks highest-priority first. Instead it runs them lowest-first, and the moment two tasks share a priority it crashes with TypeError: '<' not supported between instances of 'Task' and 'Task'. The heap operations themselves are used correctly. Find both bugs.
1import heapq2 3 4class Task:5 def __init__(self, name, priority):6 self.name = name7 self.priority = priority8 9 10def run_order(tasks):11 """Names in execution order: highest priority first."""12 pq = []13 for t in tasks:14 heapq.heappush(pq, (t.priority, t))15 order = []16 while pq:17 _, t = heapq.heappop(pq)18 order.append(t.name)19 return order20 21 22print(run_order([Task("deploy", 3), Task("lint", 1), Task("test", 2)]))23# ['lint', 'test', 'deploy'] — expected ['deploy', 'test', 'lint']24 25print(run_order([Task("a", 1), Task("b", 1)]))26# TypeError: '<' not supported between instances of 'Task' and 'Task'Your task
- Is
heapqa min-heap or a max-heap? What doesheappopreturn, and what does that mean for "highest priority first"? - Explain the
TypeError: how does Python compare the tuples(1, task_a)and(1, task_b), and why does the first test case never hit this? - Fix both problems with the standard idiom: negation plus a tie-breaking counter. Why must the counter sit *between* the priority and the task?
- What extra property does the counter give you among equal-priority tasks?
- Priorities are numbers here. What if they were strings ("high"/"low"), where negation is impossible? Give two options.
- State the complexity of
run_order.
DebuggingEdge CasesImplementation
Work it out
Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.
Reveal
Progressive — each section builds on the previous one.
The bug
Why it happens
The fix
Edge cases
Complexity
Self-check
Tick what your analysis covered. Be honest — this feeds your readiness profile.