Question

In: Computer Science

Redesign topsort so it selects the LAST NODE in each iteration, rather than the first. def...

Redesign topsort so it selects the LAST NODE in each iteration, rather than the first.

def topsort(G):

count = dict((u, 0) for u in G) # The in-degree for each node

for u in G:

for v in G[u]:

count[v] += 1 # Count every in-edge

Q = [u for u in G if count[u] == 0] # Valid initial nodes

S = [] # The result

while Q: # While we have start nodes...

u = Q.pop() # Pick one

S.append(u)    # Use it as first of the rest

for v in G[u]:

count[v] -= 1 # "Uncount" its out-edges

if count[v] == 0: # New valid start nodes?

Q.append(v) # Deal with them next

return S

Solutions

Expert Solution

topsort will function as reverse. In this topological sorting is used to increase the accuracy.

for getting your final output you have to re-arrage some function and apply some extra logic these will work in most of test cases , but you got any problem please rebuild some functions and try to execute.The program will work correct.

also Depth First Search can be used.

for example:

dag <- DAG(a ~ b, c ~ a + b, d ~ c + b)

dag

topOrder(dag)

topSort(dag)


#solution
  
 
class Test: 
    def __init__(self, vertices): 
        self.Test = defaultdict(list)  
        self.V = vertices 
  
    
    def adeg(self, u, v): 
        self.Test[u].append(v) 
  
  
    def toposort(self):  
        in_degree = [0]*(self.V) 
          
        
        for i in self.Test: 
            for j in self.Test[i]: 
                in_degree[j] += 1
  
        
        queue = [] 
        for i in range(self.V): 
            if in_degree[i] == 0: 
                queue.append(i) 
  
        
        cnt = 0
  
       
        t_order = [] 
  
       
        while queue: 
  
           
            u = queue.pop(0) 
            t_order.append(u) 
  
            
            for i in self.Test[u]: 
                in_degree[i] -= 1
                # If in-degree becomes zero, add it to queue 
                if in_degree[i] == 0: 
                    queue.append(i) 
  
            cnt += 1
  
        
        if cnt != self.V: 
            print("exists a cycle in  Test")
        else : 
           
            print(t_order) 
  
  
g = Test(6) 
g.adeg(5, 2); 
g.adeg(5, 0); 
g.adeg(4, 0); 
g.adeg(4, 1); 
g.adeg(2, 3); 
g.adeg(3, 1); 
  
print("Sort of the given Test")
g.toposort() 
  
 

the above code will run in only case when you import defaultdict in your local system also don't forget to write the import statements which are essential.


Related Solutions

Suppose that money demand depends on consumption rather than on income, so that the equation for...
Suppose that money demand depends on consumption rather than on income, so that the equation for the money market becomes: M/P = L [r, C(Y-T)]. Analyze the impact of a tax cut in a small open economy on the exchange rate and income under both floating and fixed exchange rates
Imagine that the Earth’s rotational axis was tilted 90 degrees rather than 23.5 degrees (so the...
Imagine that the Earth’s rotational axis was tilted 90 degrees rather than 23.5 degrees (so the polar axis would point towards the Sun twice a year). Describe the apparent motion of the Sun and stars over a 24-h period on the winter solstice from (a) the North Pole, (b) the equator, and (c) the South Pole. Note that the Sun’s angular diameter is 0.5 degrees.
"As the First World War demonstrated, economic integration leads to more, rather than less, violent conflict."...
"As the First World War demonstrated, economic integration leads to more, rather than less, violent conflict." Discuss. (Please discuss the answer within 800 words - at most 1000 words! Thanks!)
why has technology become so important than when it was first invented?
why has technology become so important than when it was first invented?
Why do you think so much money and attention goes towards genetic research rather than towards...
Why do you think so much money and attention goes towards genetic research rather than towards improving social conditions?
For each, indicate whether the first item is (greater than, equal to, less than) the second...
For each, indicate whether the first item is (greater than, equal to, less than) the second item oxygen content in the pulmonary veins      ___________       oxygen content in the carotid arteries Answer 1Choose...greater thanequal toless than maximum pressure in the aorta ___________     maximum pressure in the left atrium   Answer 2Choose...greater thanequal toless than blood flow through the lungs ____________ blood flow through the kidneys Answer 3Choose...greater thanequal toless than flow of blood through a dilated vessel _____________ flow of blood through...
Both the US and Canada have federal, rather than unitary, constitutions. In each country, legislative powers...
Both the US and Canada have federal, rather than unitary, constitutions. In each country, legislative powers are divided between two levels of government. However, the constitutions are not identical and the powers granted to each federal government are considerably different. Compare and contrast the roles of the two federal governments in developing their respective health care systems. Describe the health programs each federal government is responsible for funding and/or administering as appropriate. Has Canada’s constitution has made it easier, or...
: Explain why Tokyo Disney Resort was so much more successful at first than Disneyland Paris...
: Explain why Tokyo Disney Resort was so much more successful at first than Disneyland Paris at first.
Consider a variant of the matrix-chain multiplication problem in which the goal is to parenthesize the sequence of matrices so as to maximize, rather than minimize, the number of scalar multiplications.
Consider a variant of the matrix-chain multiplication problem in which the goal is to parenthesize the sequence of matrices so as to maximize, rather than minimize, the number of scalar multiplications. Does this problem exhibit optimal substructure?
Trish receives $480 on the first day of each month. Josh receives $480 on the last...
Trish receives $480 on the first day of each month. Josh receives $480 on the last day of each month. Both Trish and Josh will receive monthly payments for next 3 years. At a 9.5 percent annual rate, compounded monthly, what is the highest present value amount?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT