简体   繁体   English

Python中边列表的生成树列表

[英]Spanning Tree list from edge list in Python

I am trying to figure out how to print a Spanning Tree list from a given list of edges.我想弄清楚如何从给定的边列表打印生成树列表。 For example, if I read in:例如,如果我读入:

0 1 0 1

2 1 2 1

0 2 0 2

1 3 1 3

I want to print out a Spanning Tree list of:我想打印出一个生成树列表:

[[1], [0,2,3], [1], [1]] [[1], [0,2,3], [1], [1]]

I know how to create an adjacency list using the code:我知道如何使用代码创建邻接列表:

n = int(input("Enter number of vertices: "))
adjList = [[] for i in range(n)]
with open("graph.txt") as edges:
    for line in edges:
        line = line.replace("\n", "").split(" ")
        adjList[int(line[0])].append(int(line[1]))
        adjList[int(line[1])].append(int(line[0]))
    print(l)

But creating a Spanning Tree is a different story.但是创建生成树是另一回事。 Given that the Spanning Tree would be unweighted, I am not sure if I need to use some version of Prim's Algorithm here?鉴于生成树将是未加权的,我不确定是否需要在这里使用某些版本的 Prim 算法?

Any help is appreciated!任何帮助表示赞赏!

This implementation is based on the networkx package (documentation for it is here ).这个实现基于networkx包(它的文档在这里)。 Note that there's a few different spanning trees that I think you can get for that set of connections.请注意,我认为您可以为这组连接获得一些不同的生成树。 This code will represent the spanning tree by its collection of edges, but I'll see if I can modify it to represent the tree the way you prefer.这段代码将通过边的集合来表示生成树,但我会看看是否可以修改它以按照您喜欢的方式来表示树。

import networkx as nx

def spanning_tree_from_edges(edges):
    graph = nx.Graph()

    for n1, n2 in edges:
        graph.add_edge(n1, n2)

    spanning_tree = nx.minimum_spanning_tree(graph)
    return spanning_tree

if __name__ == '__main__':
    edges = [(0, 1), (2, 1), (0, 2), (1, 3)]
    tree = spanning_tree_from_edges(edges)
    print(sorted(tree.edges()))

Output输出

[(0, 1), (0, 2), (1, 3)]

This alternative seems to represent the tree as the collection of node connections (ie in the format you want).这种替代方法似乎将树表示为节点连接的集合(即以您想要的格式)。 Note that this collection is different because it's a different spanning tree to what you get:请注意,此集合是不同的,因为它与您获得的生成树不同:

if __name__ == '__main__':
    edges = [(0, 1), (2, 1), (0, 2), (1, 3)]
    tree = spanning_tree_from_edges(edges)
    print([list(nx.all_neighbors(tree, n)) for n in tree.nodes()])

Output输出

[[1, 2], [0, 3], [0], [1]]

Starting Graph起始图

Generated Spanning Tree生成的生成树

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM