创建邻接矩阵的快捷方式

时间:2016-08-22 19:46:47

标签: python adjacency-matrix minimum-spanning-tree

我需要一个我编写的python代码的简短版本。基本上我所拥有的是一个文本文件,其值如下所示:

x
a b c
d e f

第一行是节点数。从第二行开始,将值读入NODE1,NODE2,Weight。我正在使用这些值并从中创建一个邻接矩阵。这将是一个无向图,因此矩阵[u] [v]将等于矩阵[v] [u]。 这是我的代码:

with open(filename, 'r') as textfile:
            firstLine = int(textfile.readline())
            for line in textfile:
                a, b, c = line.split()
                a = int(a)
                b = int(b)
                c = float(c)
                graph[a][b] = graph[b][a] = c

现在我需要将对角线填充为零,将其他未分配的索引填充为无穷大。

2 个答案:

答案 0 :(得分:1)

with open(filename, 'r') as textfile:
    file_lines = text_file.readlines()

    # Initialize graph with -1 value, i.e. path do not exists representing infinite
    # Note: If negative weight is allowed, use the value which you want to symbolize infinte
    total_node = int(file_lines[0])
    my_graph = [[-1]*total_node]*total_node

    # Update weight based on available path
    for line in file_lines[1:]:
        s = line.split()
        u, v, w = int(s[0]), int(s[1]), float(s[2])
        my_graph[u][v] = my_graph[v][u] = w

    # Update diagonals to zero
    for i in range(total_node):
        my_graph[i][i] = my_graph[i][total_node - (i+1)] = 0

答案 1 :(得分:0)

我不确定更简单,但是使用numpy reshape,您可以在填充权重之前创建默认矩阵,而不使用显式循环。这里n是大小。

In [20]: n=4; np.reshape(np.array(([0]+[float("inf")]*n)*(n-1)+[0]),[n,n])
Out[20]:
array([[  0.,  inf,  inf,  inf],
       [ inf,   0.,  inf,  inf],
       [ inf,  inf,   0.,  inf],
       [ inf,  inf,  inf,   0.]])