Schedule tasks with prerequisites using Kahn's algorithm. Detect if a cycle exists for invalid schedules. Output must support parallel execution groups identifying which tasks can run simultaneously at each step.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Producing Kahn’s algorithm with parallel execution groups
python
from collections import defaultdict, deque
def schedule(tasks, prerequisites):
"""
Schedule tasks with prerequisites using Kahn's algorithm.
Returns a list of lists, where each inner list contains tasks
that can run in parallel at that step.
If a cycle is detected, returns (None, True).
Args:
tasks: iterable of tasks (hashable)
prerequisites: list of (pre, post) pairs where pre must run before post
Returns:
(schedule: List[List[task]], has_cycle: bool)
"""
graph = defaultdict(list)
indegree = {task: 0 for task in tasks}
# Include tasks only in prerequisites but not in tasks
for pre, post in prerequisites:
graph[pre].append(post)
if post not in indegree:
indegree[post] = 0
if pre not in indegree:
indegree[pre] = 0
indegree[post] += 1
zero_indegree = deque([node for node, deg in indegree.items() if deg == 0])
schedule_result = []
visited_count = 0
while zero_indegree:
current_group = list(zero_indegree)
schedule_result.append(current_group)
zero_indegree.clear()
for node in current_group:
visited_count += 1
for neighbor in graph[node]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
zero_indegree.append(neighbor)
if visited_count != len(indegree):
# Cycle detected
return None, True
return schedule_result, False
# Example usage
if __name__ == "__main__":
tasks = ['A', 'B', 'C', 'D', 'E', 'F']
prerequisites = [('A', 'D'), ('F', 'B'), ('B', 'D'), ('F', 'A'), ('D', 'C')]
schedule_groups, has_cycle = schedule(tasks, prerequisites)
if has_cycle:
print("Cycle detected in tasks, no valid schedule possible.")
else:
print("Parallel execution groups:")
for i, group in enumerate(schedule_groups, 1):
print(f"Step {i}: {group}")
# Time complexity: O(V + E), where V is number of tasks and E is number of prerequisites.
```</think>
Here is a self‑contained Python implementation of Kahn’s algorithm that returns the parallel execution groups (tasks with all prerequisites satisfied at each step). It also detects cycles and reports an invalid schedule.
```python
from collections import defaultdict, deque
from typing import Any, Iterable, List, Tuple, Dict
def parallel_kahn(
tasks: Iterable[Any],
prerequisites: Iterable[Tuple[Any, Any]],
) -> Tuple[List[List[Any]], bool]:
"""
Compute a schedule using Kahn's algorithm.
Returns (levels, has_cycle), where levels is a list of lists,
each inner list containing tasks that can run in parallel at that stage.
has_cycle is True if no valid topological order exists.
:param tasks: An iterable of task identifiers (e.g., strings or ints).
:param prerequisites: An iterable of (u, v) pairs meaning u must precede v.
"""
graph: Dict[Any, List[Any]] = defaultdict(list)
indegree: Dict[Any, int] = {}
# Initialize indegree for all tasks
for t in tasks:
indegree[t] = 0
# Build graph and indegree counts
for pre, post in prerequisites:
graph[pre].append(post)
if pre not in indegree:
indegree[pre] = 0
if post not in indegree:
indegree[post] = 0
indegree[post] += 1
# Start with all nodes of indegree 0
queue = deque([node for node, deg in indegree.items() if deg == 0])
levels: List[List[Any]] = []
visited = 0
while queue:
# All current zero-indegree nodes form the next parallel group
current_group = list(queue)
levels.append(current_group)
queue.clear()
for node in current_group:
visited += 1
for neighbor in graph[node]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
has_cycle = (visited != len(indegree))
if has_cycle:
return [], True # Invalid schedule due to cycle
return levels, False
# Example usage:
if __name__ == "__main__":
tasks = ["A", "B", "C", "D", "E", "F"]
prerequisites = [
("A", "D"),
("F", "B"),
("B", "D"),
("F", "A"),
("D", "C"),
]
schedule, cycle = parallel_kahn(tasks, prerequisites)
if cycle:
print("No valid schedule (cycle detected).")
else:
print("Parallel execution groups:")
for i, group in enumerate(schedule, 1):
print(f"Step {i}: {group}")
How it works:
Builds an adjacency list (graph) and an indegree table (indegree).
Initializes a queue with all zero‑indegree tasks; these form the first parallel group.
Repeatedly takes the current zero‑indegree set as a group, “removes” them, and decrements neighbors’ indegrees, collecting newly zero‑indegree nodes for the next group.
If the number of visited tasks is less than the total, a cycle exists and no valid ordering is possible.