Question

In: Computer Science

You need to complete n courses in order to complete your degree. Some of these courses...

You need to complete n courses in order to complete your degree. Some of these courses have prerequisites, for example: “course 1 has to be completed before course 3”. Your goal is to find an order to take all n courses and complete your degree.


Observe the following input file. The first line in the file has 2 numbers n and p where n is number of courses and p is the number of prerequisites.


Input:
5 3
1 2
3 1
4 5


The first line indicates that there are 5 courses numbered 1 to 5 and 3 prerequisites “1 should be taken before 2”, “3 should be taken before 1” and “4 should be taken before 5”
The output should an ordered list of the sequence of courses or “Not possible”. You can print any valid sequence. For the above example the output can be 3, 4 1, 2,5 or 4, 3, 1, 5, 2 etc…

Using topological sort (DFS or source removal) create a python algorithm.

Solutions

Expert Solution

  • Below is the detailed implementation of the above problem in PYTHON with code and output shown.
  • For better understanding please read the comments mentioned in the code.
  • The basic idea of the algorithm is to see the courses as a set of nodes in a graph in which each edge i.e, an edge is a prerequisite course(say u) -> this course(say v) is seen as a directed edge and using topological sort to generate an order in which every node such that it is a prerequisite course(say node u) comes first in order than the this course(say node v). So for generating topological order we also have to check if cycle exists in graph or not as if cycle exists then there cannot be any topological order of the graph nodes.
  • CODE:

#function which creates a topological order of the given nodes of a graph, if possible
def topo(node,graph,l):
#visit current node
vis[node]=1
#if node as some neighbor
if node in graph.keys():
#iterate through all neighbors
for neighbor in graph[node]:
#if unvisited
if vis[neighbor]==0:
#call topo() recursively for this node
topo(neighbor,graph,l)
#after exploring all the subtree of node add it to list
l.append(node)
  
#driver code

#input n and p
n,p=list(map(int,input().split()))
#dictionary t store graph
graph={}
#take input all edges
for i in range(p):
#u->v is a directed edge
u,v=list(map(int,input().split()))
#if u exists in dict then add v to keys of it
if u in graph.keys():
graph[u].append(v);
#otherwise create a new list with v as it's only element
else:
graph[u]=[v]
  
#list to store the topological order of nodes
order=[]
#create a visited list to check if a node is visited or not, initially all unvisited
vis=[False]*(n+1)
#for every unvisited node call topo()
for i in range(1,n+1):
if vis[i]==0:
topo(i,graph,order)
#reverse order list to get the actual topological sort
order=order[::-1]

#now to check of the cycle exists in the graph or not, if cycle exist then topological sort not possible
#create a dict to store the order of nodes in topological order we got i.e, order
store={}
#store each node with their indices in order list
for ind,ele in enumerate(order):
store[ele]=ind
  
#initially set cycle to false
cycle=False
#for each node from 1 to n
for i in range(1,n+1):
#if node has neighbors
if i in graph.keys():
#for each neighbor
for nodes in graph[i]:
#if index of neighbor(or child) is less than that of parent then cycle exists
if store[nodes]<store[i]:
#matk cycle as true and break
cycle=True
break
#if cycle true the break from loop
if cycle==True:
break
#if cycle exists in graph then topological order not possible
if cycle==True:
print("Not possible")
#otherwise print the order
else:
print(*order)

  • INPUT/OUTPUT:
  1. 5 3
    1 2
    3 1
    4 5
    4 5 3 1 2
  2. 4 6
    1 2
    1 3
    2 3
    3 1
    3 4
    4 4
    Not possible
  • Below are the screenshot attached for the code and input/output for better clarity and understanding.

CODE

INPUT/OUTPUT

So if you still have any doubt regarding this solution please feel free to ask it in the comment section below and if it is helpful then please upvote this solution, THANK YOU.


Related Solutions

Q2) In order for a student to register for courses at UHV, a student need to...
Q2) In order for a student to register for courses at UHV, a student need to login in to the system, search for classes, select certain classes and submit his/her request. Create a sequence diagram for that. Q3) Create a UML class diagram for the following description, your UML should show associations with cardinality; generalizations if any. Each class should at least have two attributes. (hint: the easiest way to identify classes is to look for nouns) E-gaming Store: An...
You might need to conduct some research of your own to complete this activity. Briefly describe...
You might need to conduct some research of your own to complete this activity. Briefly describe (30 to 50 words each) what each of the terms refer to: Assets. Liabilities. Expenses. Equity. (please answer from the perspective of Australian Accounting Environment) (Please type up your answer)
You need to order US $100,000 worth of reams of paper from China to complete an...
You need to order US $100,000 worth of reams of paper from China to complete an order from an important commercial customer in 30 days. The current rate of exchange is USD/CNY = 6.5766. Ignoring other transaction expenses associated with the order, how many Yuan would you need to pay the Chinese supplier? Define the meaning of foreign exchange. Assuming that you have the choice to pay immediately or in 30 days, define, describe, and provide examples of how you...
From your math courses, you may recall that some number sequences can be defined as a...
From your math courses, you may recall that some number sequences can be defined as a cumulative sum of previous terms. With this nature, we can construct a new sequence called K sequence as shown below: K(0) = 2; K(1) = 1; K(n) = (K(n-1) + K(n-2))2, n > 1. For this lab, you are to write a python function Kseq(start,stop,step) that when passed the definition of a sequence of numbers in terms of a start, stop, and step size...
As you complete your reading on the fats in your diet, there are some issues I...
As you complete your reading on the fats in your diet, there are some issues I would like you to address. First, fats are found in many foods but some are better for you than others. Secondly, what is a monounsaturated fat and why do you need to know which foods to eat to get this fat into your diet? Think blood chemistry. Lastly, heart disease is the leading cause of death in this country. Heart disease has maintained its...
You have just received an order from an Internet retailer for some equipment you need for...
You have just received an order from an Internet retailer for some equipment you need for a business presentation. Unfortunately, some of the equipment is damaged. Write a letter to the retailer in which you explain the damage, express your dissatisfaction with the shipment, and describe what you want the retailer to do to fulfill your shipment. Develop a response that includes examples and evidence to support your ideas, and which clearly communicates the required message to your audience. Organize...
In order to complete your case analysis successfully, you should consider identifying the role you are...
In order to complete your case analysis successfully, you should consider identifying the role you are playing, assessing the financial reporting landscape considering the user needs, constraints, and business environment, identifying the issues, analyzing the issues (qualitatively and quantitatively), and providing a recommendation for each issue identified in the case. You are required to prepare for the case before the class and bring any documents that will support your analysis. An average grade will come from you answering questions with...
In order to complete your case analysis successfully, you should consider identifying the role you are...
In order to complete your case analysis successfully, you should consider identifying the role you are playing, assessing the financial reporting landscape considering the user needs, constraints, and business environment, identifying the issues, analyzing the issues (qualitatively and quantitatively), and providing a recommendation for each issue identified in the case. You are required to prepare for the case before the class and bring any documents that will support your analysis. An average grade will come from you answering questions with...
In order to achieve your vision and your goals, you will need objectives (outcomes for your marketing team).
In order to achieve your vision and your goals, you will need objectives (outcomes for your marketing team). List three marketing objectives that you want your marketing team to accomplish for your company. Be concise, we do not need an academic paper and discussion, only that the objectives be clearly understand. You do not have to know how you are going to achieve those goals at this point, only that you want them done somehow.You should work as much as...
Please Use your keyboard (Don't use handwriting) Thank you.. Courses Name: Environmental Health need new and...
Please Use your keyboard (Don't use handwriting) Thank you.. Courses Name: Environmental Health need new and unique answers, please. (Use your own words, don't copy and paste) Please i need more than 500 words Q. 1. Explain the environmental pollution (air, water, soil and food) health issues in KSA. Q. 2. Describe the sources and pathways of exposure groups. Q. 3. Enumerate methods to control and prevent pollution. Q. 4. How public health policy and environmental law supporting to promote...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT