Question

In: Computer Science

Can you solve and send me the original code which I can copy and paste plz....

Can you solve and send me the original code which I can copy and paste plz. Thank you.

Kahn's Algorithm

Implement Kahn's Algorithm for giving a topological ordering of a graph as discussed in class. The input graph will be in adjacency list format.

1. Count the in-degree (number of edges ending at) each vertex.

2. Create a queue of nodes with in-degree 0.

3. While the queue is not empty:

a. Add the first element in the queue to the ordering.

b. Decrement the in-degree of each of the first element’s neighbors.

c. Add any neighbors that now have in-degree 0 to the queue.

d. Remove the first element from the queue.

4. If the ordering doesn't contain all nodes then the graph had a cycle and we return None

5. Else we return the ordering

 

graph = [

[1, 3],

[],

[3, 6, 7],

[6],

[],

[],

[],

[5, 4],

]

order = topological(graph)

print(order)

[0, 2, 1, 3, 7, 6, 4, 5] # one POSSIBLE ordering

order.index(0) < order.index(3)

order.index(0) < order.index(1)

order.index(2) < order.index(3)

order.index(2) < order.index(6)

order.index(2) < order.index(5)

order.index(3) < order.index(6)

order.index(7) < order.index(5)

from collections import deque

#complete following code

def topological(graph):
in_deg = [0 for _ in range(len(graph))]
  
for node1 in range(len(graph)):
for node2 in graph[node1]:
in_deg[node2] += 1
  
queue = deque()
"""
Iterate over all the nodes and append the nodes with in-degree 0 to the queue
"""
# your code here
  
ordereing = []
while len(queue) > 0:
current_node = queue.popleft()
ordereing.append(current_node)

for neighbor in graph[current_node]:
in_deg[neighbor] -= 1
"""
If this neighbor in-degree now becomes 0, we need to append it to the queue
"""

# your code here
  
"""
If we couldn't process all nodes, this means there was a cycle in the graph
and the graph wasn't a DAG.
"""
if len(ordereing) != len(graph):
return None
  
return ordereing

order.index(7) < order.index(4)

Solutions

Expert Solution

Solution

#Since you have only asked for the code.

from collections import deque
def topological(graph):
    in_deg = [0 for _ in range(len(graph))]
    
    for node1 in range(len(graph)):
        for node2 in graph[node1]:
            in_deg[node2] += 1
    
    queue = deque()
    """
    Iterate over all the nodes and append the nodes with in-degree 0 to the queue
    """
    for node1 in range (len(graph)):
        if in_deg[node1]==0:
            queue.append(node1)
    
    ordereing = []
    while len(queue) > 0:
        current_node = queue.popleft()
        ordereing.append(current_node)

        for neighbor in graph[current_node]:
            in_deg[neighbor] -= 1
            if in_deg[neighbor]==0:
                queue.append(neighbor)
    """
    If this neighbor in-degree now becomes 0, we need to append it to the queue
    """

    
    """
    If we couldn't process all nodes, this means there was a cycle in the graph
    and the graph wasn't a DAG.
    """
    if len(ordereing) != len(graph):
        return None
    
    return ordereing

Hope this helps! Please rate the solution if you like it.

Thanks!


Related Solutions

Please find error and fill the blank and send as I can copy and paste like...
Please find error and fill the blank and send as I can copy and paste like file or just codes if you can ? 1) #include <stdio.h> #include <stdlib.h> #define Error( Str ) FatalError( Str ) #define FatalError( Str ) fprintf( stderr, "%s ", Str ), exit( 1 ) 2) #include "list.h" #include <stdlib.h> #include "fatal.h" /* Place in the interface file */ int Equal(ElementType x, ElementType y) { return x==y; } void Print(ElementType x) { printf("%2d", x); } List...
Can you fix to me this code plz I just want to print this method as...
Can you fix to me this code plz I just want to print this method as the reverse. the problem is not printing reverse. public void printBackward() {               Node curr = head;        Node prev = null;        Node next = null;               System.out.print("\nthe backward of the linkedlist is: ");               while(curr != null) {            next = curr.next;            curr.next = prev;   ...
Can you solve it for me plz? ‘Lakeside Manufacturing’ is a boating company that specializes in...
Can you solve it for me plz? ‘Lakeside Manufacturing’ is a boating company that specializes in sailboats for sailing schools and Jules Paulson is the owner of the company. His lead foreman and second in command is Kevin Hill. There are a small core group of 15 employees who are fulltime and experienced in their trade and sailing. Unfortunately, over the summertime, the permanent employees like to take their vacation so they can go sailing. ‘Lakeside Manufacturing’ makes sure that...
I need a fresh answer. Do not copy and paste. Solve only when you have deep...
I need a fresh answer. Do not copy and paste. Solve only when you have deep subject knowledge,. Thank You Please answer the question below. prepare the journal entries for all the following related transaction (all occurring within the current year). Assume all depletion and amoritization for the full year. Also, assume all purchases were made with cash. A. An exploration company purchased land with a valuable ore deposit      Estimated ore available in the deposit (in tons)                      4,700,000     ...
Using R Studio Use the two iid samples. (You can copy and paste the code into...
Using R Studio Use the two iid samples. (You can copy and paste the code into R). They both come from the same normal distribution. X = c(-0.06, 1.930, 0.608 -0.133,0.657, -1.284, 0.166, 0.963, 0.719, -0.896) Y = c(0.396, 0.687, 0.809, 0.939, -0.381, -0.042, -1.529, -0.543, 0.758, -2.574, -0.160, -0.713, 0.311, -0.515, -2.332, -0.844, -0.942, 0.053, 0.066, 0.942, -0.861, -0.186, -0.947, -0.110, 0.634, 2.357, 0.201, -0.428, -1.661, 0.395) (a) Report 95% confidence interval for the mean of X. Should we...
Looking for an original answer. Not a copy and paste: What are the major reasons that...
Looking for an original answer. Not a copy and paste: What are the major reasons that motivate networking? Consider some of the following: What are the real/hidden costs of networks? How have networks changed the way we do business? Are some business sectors more affected than others?
can anyone explain to me according to the own simple word not copy and paste about...
can anyone explain to me according to the own simple word not copy and paste about the theory of the blanned behavior and social Learning and relate them in the dental Hyegene thank You
Please solve me this question and send me the video clip how to do it This...
Please solve me this question and send me the video clip how to do it This problem contains loops, sorting arrays, random generation, and variable matching. Include an analysis (data requirements) and algorithm in your reply. Write a “lottery engine” program to simulate drawing lottery numbers. You will draw 7 numbers, randomly selected from 1 to 16. a) Allow the user to enter their own selection of numbers first, Example numbers: 2 3 7 9 10 11 15 b) then...
IF YOU COPY AND PASTE THE ANSWER FROM YAHOO ANSWERS, I WILL NOT RATE AND I...
IF YOU COPY AND PASTE THE ANSWER FROM YAHOO ANSWERS, I WILL NOT RATE AND I WILL ALSO REPORT FOR NON-ORIGINAL WORK. Please stop copy and pasting Yahoo! Answers, it is wrong, that is why I am posting this ? on here. A fuel oil is composed of C10H22 and C12H26 in an unknown ratio (Note, there are no other significant components in the fuel oil). When the fuel oil is burned with 20% excess air the exhaust is tested...
I was wondering if you can tell me if the following code is correct and if...
I was wondering if you can tell me if the following code is correct and if its not can it be fixed so it does not have any syntax errors. Client one /** * Maintains information on an insurance client. * * @author Doyt Perry/<add your name here> * @version Fall 2019 */ public class Client { // instance variables private String lastName; private String firstName; private int age; private int height; private int weight; /** * First constructor for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT