[英]Shortcut to creating an adjacency matrix
我需要我編寫的python代碼的簡短版本。 所以基本上我是一個文本文件,其值如下:
x
a b c
d e f
第一行是節點數。 從第二行開始,將值讀入NODE1,NODE2,Weight。 我正在使用這些值並從中創建一個鄰接矩陣。 這將是無向圖,因此matrix [u] [v]將等於matrix [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
現在,我需要將對角線填充為零,並將其他未分配的索引填充為無窮大。
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
我不確定是否更簡單,但是通過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.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.