如何在python

时间:2017-12-05 21:34:17

标签: python graph graph-theory adjacency-matrix

我有文本文件,其中包括:

1 2
1 5
2 3
2 5
3 4

我是python中的新手,如何将这些数据从.txt转换为python中的邻接矩阵?非常感谢提前。

2 个答案:

答案 0 :(得分:0)

这是代码

将从输入文件中读取并构建邻接矩阵

f = open("graph.txt", 'r')
graph = {}
n = 0
for i in f.readlines():
    nodes = i.split(" ")
    n1 = int(nodes[0])
    n2 = int(nodes[1])
    if n < n1 and n1 > n2:
        n = n1
    if n < n2 and n2 > n1:
        n = n2
    if n1 not in list(graph):
        graph[n1] = []
    adjacencyList = graph[n1]
    adjacencyList.append(n2)
    graph[n1] = adjacencyList

adjacencyMatrix = []
for i in range(1,n+1):
    row = []
    for j in range(1,n+1):
        if i in list(graph) and j in graph[i]:
            row.append(1)
        else:
            row.append(0)
    adjacencyMatrix.append(row)

for i in range(n):
    row = ""
    for j in range(n):
        row += str(adjacencyMatrix[i][j])+" "

    print(row)

答案 1 :(得分:0)

我猜你正试图解决一些图形问题。读取所有行并创建一个方形矩阵,其中rows = columns =列表中的最大数

然后,根据图表是否具有方向性,您应该用1填充矩阵中的位置。

例如

Matrix = [[0 for x in range(n)] for y in range(n)] 

其中n是图中的最大节点数。

然后你的第一行应该被分配到

Matrix[0][1] = 1 
Matrix[1][0] = 1 //this line if graph is not directional