


Python implementation of topological sorting code example of directed acyclic graph
The content of this article is about the code example of topological sorting of directed acyclic graph in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Topological sorting of Python directed acyclic graph
The official definition of topological sorting is: from a partial order on a certain set to get the upper part of the set A total order of , this operation is called topological sorting. Personally, I believe that topological sorting is a sorting method that introduces the concept of in-degree into the basic traversal method of graphs and implements it around in-degree. Topological sorting is similar to the sorting of mro rules in Python multiple inheritance. If you want to study the mro rules in depth C3 algorithm, you might as well learn about the topological sorting of DAG (Directed Acyclic Graph).
In-degree: refers to the sum of the number of points pointed to a node in the directed graph
Directed Acyclic Graph: Directed Acyclic Graph, DAG for short. If you are familiar with machine learning, you will definitely be familiar with DAG, such as ANN , DNN, CNN, etc. are all typical DAG models. I won’t elaborate too much on these models here. Those who are interested can learn by themselves.
Take a directed acyclic graph as an example, as shown below:
# 定义图结构graph = { "A": ["B","C"], "B": ["D","E"], "C": ["D","E"], "D": ["F"], "E": ["F"], "F": [],}
A points to The element pointed to is B, the element pointed to by C
B is D, the element pointed to by E
C is D, the element pointed to by E
D is pointed to by F
E, and the element pointed to by F
F The element of is empty
That is, the in-degree of A is 0, the in-degree of B is 1, the in-degree of C is 1, the in-degree of D is 2, the in-degree of E is 2, and the in-degree of F is 2
In the topological sorting of DAG, each time a point with an in-degree of 0 is selected and added to the topological queue, and then all edges connected to this point are deleted.
First find the point A with an in-degree of 0, take A out of the queue, add it to the result and remove the pointers related to A, that is, reduce the in-degrees of B and C by 1 to 0 and add B, C is added to the queue, and then the node with an in-degree of 0 is taken out from the head of the queue, and so on, and finally the result is output to complete the topological sorting of the DAG.
def TopologicalSort(G): # 创建入度字典 in_degrees = dict((u, 0) for u in G) # 获取每个节点的入度 for u in G: for v in G[u]: in_degrees[v] += 1 # 使用列表作为队列并将入度为0的添加到队列中 Q = [u for u in G if in_degrees[u] == 0] res = [] # 当队列中有元素时执行 while Q: # 从队列首部取出元素 u = Q.pop() # 将取出的元素存入结果中 res.append(u) # 移除与取出元素相关的指向,即将所有与取出元素相关的元素的入度减少1 for v in G[u]: in_degrees[v] -= 1 # 若被移除指向的元素入度为0,则添加到队列中 if in_degrees[v] == 0: Q.append(v) return resprint(TopologicalSort(graph))
Output results:
['A', 'C', 'B', 'E', 'D', 'F']
The code output results are consistent with the above analysis
The above is the detailed content of Python implementation of topological sorting code example of directed acyclic graph. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool