0

I'm trying to rank/resolve a set of tasks with dependencies among them. For example, I have below objects representing tasks

class Task:
    def __init__(self, name):
        self.name = name
        self.execute_after = []

if __name__ == "__main__":
    task_A = Task("A")
    task_B = Task("B")
    task_C = Task("C")
    task_D = Task("D")

    task_A.execute_after = [task_C, task_D]
    task_B.execute_after = []
    task_C.execute_after = [task_B, task_D]
    task_D.execute_after = [task_B]

Now I need to be able to rank the order in which these tasks need to be executed.

For example, here

  • task_B would be executed first as it has no dependency.
  • Next, task_D would be executed as its dependency is resolved
  • Next, task_C would be executed as both its dependencies are resolved.
  • Finally task_A would be executed.

I could do a DFS but trying to figure out if there is an alternative way of ranking this or coming up with the correct order of solving this problem?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Have you considered [`TopologicalSorter`](https://docs.python.org/3/library/graphlib.html#graphlib.TopologicalSorter)? – Nelewout Feb 09 '22 at 18:17
  • @NielsWouda unfortunately I'm constrained to use python 3.8 which doesn't have this lib. https://docs.python.org/3.8/library/datatypes.html – Badri Narayanan Feb 09 '22 at 18:37
  • You could look at the [source code](https://github.com/python/cpython/blob/3.10/Lib/graphlib.py) and backport it? It's pure Python, and as far as I can see does not use any features that are not already present in Py 3.8. Then you can always switch it out for the built-in, when you eventually upgrade to a more recent Python version. – Nelewout Feb 09 '22 at 21:32
  • @NielsWouda thanks a ton for the suggestion. It gave me pointers to look in the right direction. I tried re-using code from the leetcode solution [link](https://leetcode.com/problems/course-schedule-ii/solution/) and it solved my purpose. – Badri Narayanan Feb 09 '22 at 23:41

0 Answers0