Task Dependencies
Start Timer
0:00:00
Let’s say we’re building a task manager for a pool of workers, where a task can only start once all of its dependencies are done. Write a class called TaskManager with these methods:
add_task(task_id, priority, deps)adds a task.get_next(worker)gives the worker the highest-priority ready task and returns its id, orNoneif nothing is ready or the worker already has a task.complete(task_id)returnsTrueif the task was running andFalseotherwise.cancel(task_id)stops a task along with every task that depends on it, directly or indirectly, and returns the ids it cancelled.
Rules
- A higher number means higher priority, and ties go to the task added first.
- Raise a ValueError for a duplicate task id or a dependency that hasn’t been added.
- Cancelling a task that is done or already cancelled returns an empty list.
- A task added with a cancelled dependency is cancelled right away.
Example:
tm = TaskManager()
tm.add_task("a", 1, [])
tm.add_task("b", 5, ["a"])
tm.add_task("c", 3, ["b"])
tm.get_next("w1") # "a"
tm.cancel("a") # ["a", "b", "c"] in any order
.
.
.
.
.
.
.
.
.
Comments