[Basic Python Sorting Algorithm]-topological sorting

Source: Internet
Author: User

Topological sorting is a sort of Directed Acyclic graphs, which meets the following two conditions:

1. Each vertex appears only once;

2. If A is ranked before B in the sequence, there is no path from B to A in the figure.



In the above undirected directed graph, v indicates vertices: v = ['A', 'B', 'C', 'D', 'E'], and e Indicates directed edges: e = [('A', 'B'), ('A', 'D'), ('B', 'C'), ('D ', 'C'), ('D', 'E'), ('E', 'C')], the Code is as follows:

Def indegree0 (v, e): if v = []: return Nonetmp = v [:] for I in e: if I [1] in tmp: tmp. remove (I [1]) if tmp = []: return-1for t in tmp: for I in range (len (e): if t in e [I]: e [I] = 'todel '# placeholder, and then delete if e: eset = set (e) eset. remove ('todel ') e [:] = list (eset) if v: for t in tmp: v. remove (t) return tmpdef topoSort (v, e): result = [] while True: nodes = indegree0 (v, e) if nodes = None: breakif nodes =-1: print ('There \'s a circle. ') return Noneresult. extend (nodes) return resultv = ['A', 'B', 'C', 'D', 'E'] e = [('A ', 'B'), ('A', 'D'), ('B', 'C'), ('D ', 'E'), ('E', 'C')] res = topoSort (v, e) print (res)

The indegree0 function returns the vertex with an inbound value of 0 and deletes its adjacent edge in v and e. If no vertex exists in the v list, None is returned, if there are still vertices in the v list but the vertex with an inbound degree of 0 cannot be found, it indicates that the directed graph has a ring and-1 is returned. The topoSort function constantly extracts the vertex with an inbound degree of 0 from the directed graph, and finally the topological sorting sequence. The output is as follows:

['a', 'b', 'd', 'e', 'c']

Consider a case where a ring exists and add a side c-> d, as shown in:


The output is as follows:

there's a circle.None

Reprinted Please note:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.