How to find the minimum number of semesters needed to study all courses in Python ?

  Python Questions & Answers

Dear reader, today in this tutorial, learn how to find the minimum number of semesters required to study all courses in Python?

We have studied all the courses we are studying in one semester. We need to find the minimum semester required to study all courses. And if there is no way to study all the courses, then return -1.

Therefore, if the input is like N = 3, relation = [[1,3], [2,3]], then the output will be 2 because in the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.

Program to Parallel courses

class program(object):
   def minimumSemesters(self, n, relations):
      courses = n
      visited = [False for i in range(n+1)]
      queue = []
      graph = [[] for i in range(n+1)]
      in_degree = [0 for i in range(n+1)]
      for i in relations:
         graph[i[0]].append(i[1])
         in_degree[i[1]]+=1
      semeseter = 1
      for i in range(1,n+1):
         if not in_degree[i]:
            queue.append(i)
            visited[i] = True
         semester = 1
         courses -= len(queue)
         while queue and courses:
            current_size = len(queue)
            while current_size:
               current_course = queue[0]
               queue.pop(0)
               current_size-=1
               for i in graph[current_course]:
                  in_degree[i]-=1
                  if not visited[i] and not in_degree[i]:
                     courses-=1
                     queue.append(i)
                  visited[i]=True
            semester+=1
         return semester if not courses else -1

ob = program()
print(ob.minimumSemesters(3,[[1,3],[2,3]]))

Result

-1

LEAVE A COMMENT