Home Backend Development Python Tutorial Python implementation of topological sorting code example of directed acyclic graph

Python implementation of topological sorting code example of directed acyclic graph

Oct 27, 2018 pm 04:19 PM
topological sort

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:

Python implementation of topological sorting code example of directed acyclic graph

1

2

3

4

5

6

7

# 定义图结构graph = {

    "A": ["B","C"],

    "B": ["D","E"],

    "C": ["D","E"],

    "D": ["F"],

    "E": ["F"],

    "F": [],}

Copy after login


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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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))

Copy after login

Output results:

1

['A', 'C', 'B', 'E', 'D', 'F']

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles