793. Track tasks and subtasks with completion and progress
Planning agents break a goal into tasks and subtasks and need to know what is finished. Build a small tracker for such a task tree.
Write run_tasks(ops). ops is a list of tuples:
('add', id, parent) adds a task. parent is None for a top-level task. Output 'ERROR' if id already exists or parent is not None and unknown. ('complete', id) marks the task and every task under it as done. ('status', id) outputs 'done' or 'open'. ('progress', id) outputs the fraction of leaf tasks under id (a task with no subtasks counts itself as its only leaf) that are done, rounded to 3 decimals. ('remove', id) deletes the task and everything under it.
A task with subtasks is done exactly when all of its subtasks are done. A task with no subtasks is done when it was completed. So adding a new open subtask under a done task makes that task, and its done ancestors, open again. If a task loses its last subtask through remove, it becomes a task with no subtasks again and is done only if it was itself covered by an earlier complete. Any command on an unknown id (other than add) outputs 'ERROR'.
Return the list of outputs in order.
def run_tasks(ops)Example 1
Input: run_tasks([('add', 'g', None), ('add', 'a', 'g'), ('add', 'b', 'g'), ('complete', 'a'), ('progress', 'g'), ('status', 'g'), ('complete', 'b'), ('status', 'g')])
Output: [0.5, 'open', 'done']
Constraints
- Up to 5,000 tasks.
- Ids are strings.
Hint 1
Keep children as lists so subtree walks are easy.
Hint 2
Write leaves(t) and subtree(t) helpers first.
Hint 3
Check unknown ids before any command except add.
Common mistakes
- Storing a done flag on parents and forgetting to update it when a new subtask arrives.
- Dividing by zero for a task with no subtasks; it is its own leaf.
- Not unlinking a removed task from its parent's child list.
Understand the idea
Derived state: store the minimum (leaf completion) and compute parent status from it, so the tree never holds stale flags.