Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用指示边的列表进行Python拓扑排序_Python_Algorithm - Fatal编程技术网

使用指示边的列表进行Python拓扑排序

使用指示边的列表进行Python拓扑排序,python,algorithm,Python,Algorithm,给定列表:[1,5,6],[2,3,5,6],[2,5]等(不一定按任何排序顺序),如果在一个列表中x在y之前,那么在每个有x和y的列表中x在y之前,我想找到拓扑排序的所有元素的列表(因此,如果在任何其他列表中x在y之前,那么在这个列表中x在y之前)。可能有许多解决方案,在这种情况下,我想要任何一个 在Python中实现这一点的最简单方法是什么。使用,尤其是: 我的解决方案(使用@unutbu中的一些代码) 以下是@unutbu的networkx解决方案的一个稍微简单的版本: import ne

给定列表:[1,5,6],[2,3,5,6],[2,5]等(不一定按任何排序顺序),如果在一个列表中x在y之前,那么在每个有x和y的列表中x在y之前,我想找到拓扑排序的所有元素的列表(因此,如果在任何其他列表中x在y之前,那么在这个列表中x在y之前)。可能有许多解决方案,在这种情况下,我想要任何一个

在Python中实现这一点的最简单方法是什么。

使用,尤其是:

我的解决方案(使用@unutbu中的一些代码)


以下是@unutbu的networkx解决方案的一个稍微简单的版本:

import networkx as nx
data=[[1, 5, 6], [2, 3, 5, 6], [2, 5], [7]]
G = nx.DiGraph()
for path in data:
    G.add_nodes_from(path)
    G.add_path(path)
ts=nx.topological_sort(G)
print(ts)
# [7, 2, 3, 1, 5, 6]

提取相邻对的好技巧。我认为,如果行也有一个元素,则需要调用add_节点,否则将丢失长度为1的列表。
import collections

retval = []
data = [[1,2,3], [4,5,6], [2, 5], [3, 6], [1, 7]]
in_edges = collections.defaultdict(set)
out_edges = collections.defaultdict(set)
vertices = set()
for row in data:
    vertices |= set(row)
    while len(row) >= 2:
        w = row.pop()
        v = row[-1]
        in_edges[w].add(v)
        out_edges[v].add(w)
def process(k):
    vertices.remove(k)
    retval.append(k)
    for target in out_edges[k]:
        in_edges[target].remove(k)
    for target in out_edges[k]:
        if not in_edges[target]:
            process(target)
    out_edges[k] = set()

while vertices:  # ideally, this should be a heap
    for k in vertices:
        if not in_edges[k]:
            process(k)
            break

print(retval)
import networkx as nx
data=[[1, 5, 6], [2, 3, 5, 6], [2, 5], [7]]
G = nx.DiGraph()
for path in data:
    G.add_nodes_from(path)
    G.add_path(path)
ts=nx.topological_sort(G)
print(ts)
# [7, 2, 3, 1, 5, 6]