我的代码首先接收用户输入,其中:
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
作为索引,可以是-1,所以应该是z
。你知道吗第二,访问内部循环中的
vertices[x]
,就好像它有一个节点号,但它是一个嵌套列表。相反,您需要vertices[z][x]
。为了提高性能,原则上最好为vertices[z]
创建一个名称:或:
相关问题 更多 >
编程相关推荐