【发布时间】:2017-11-19 17:52:35
【问题描述】:
我的代码首先接受用户输入,其中:
n= 图中的顶点数file= 要计算的文件
在这种情况下,我的文件是一个 .txt 文件,其中包含:
0 1
2 1
0 2
1 3
我的代码成功地将其转换为具有输出[[1, 2], [0, 2, 3], [1, 0], [1]] 的邻接列表。然而,问题是将其转换为邻接矩阵。我知道我的代码的主要问题在于这一行:
for x in range(len(vertices)):
matrix[z-1][vertices[x]] = 1
这是我的完整代码:
n = int(input("Enter the number of vertices: ")) ## E.g. 4
file = input("Enter the filename: ") ## E.g. graph.txt
vertices = []
matrix = [] ## define list
for x in range(n):
matrix.append([0]*n]) ## append a list for n, e.g. if n = 4 then [[][][][]]
vertices.append([])
f =open(file)
z = 0
for line in f: ##loop statement until no more line in file
line = line.split() ## turn every line into a list
z+=1
for y in range(len(line)):
line[y] = line[y].strip() ## remove spaces
line[y] = int(line[y]) ## converts line list into integer
## add value of line into main list
vertices[line[0]].append(line[1])
vertices[line[1]].append(line[0])
for z in range(len(matrix)):
for x in range(len(vertices)):
matrix[z-1][vertices[x]] = 1
print(vertices)
print(matrix)
【问题讨论】:
-
你为什么使用
z-1?z在该循环中的初始值为 0。
标签: python algorithm list matrix