我有这个代码:
gs = open("graph.txt", "r")
gp = gs.readline()
gp_splitIndex = gp.find(" ")
gp_nodeCount = int(gp[0:gp_splitIndex])
gp_edgeCount = int(gp[gp_splitIndex+1:-1])
matrix = [] # predecare the array
for i in range(0, gp_nodeCount):
matrix.append([])
for y in range(0, gp_nodeCount):
matrix[i].append(0)
for i in range(0, gp_edgeCount-1):
gp = gs.readline()
gp_splitIndex = gp.find(" ") # get the index of space, dividing the 2 numbers on a row
gp_from = int(gp[0:gp_splitIndex])
gp_to = int(gp[gp_splitIndex+1:-1])
matrix[gp_from][gp_to] = 1
print matrix
Run Code Online (Sandbox Code Playgroud)
文件graph.txt包含以下内容:
5 10
0 1
1 2
2 3
3 4
4 0
0 3
3 1
1 4
4 2
2 0
Run Code Online (Sandbox Code Playgroud)
前两个数字告诉我,GRAPH有5个节点和10个边.以下数字对演示节点之间的边缘.例如,"1 4"表示节点1和4之间的边缘.
问题是,输出应该是这样的:
[[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 0, 0, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
但不是那样,我明白了:
[[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
只有一个数字是不同的,我不明白为什么会发生这种情况.边缘"3 1"不存在.有人可以解释一下,问题出在哪里?
更改for i in range(0, gp_edgeCount-1):到
for i in range(0, gp_edgeCount):
Run Code Online (Sandbox Code Playgroud)
该range()函数已经执行"-1"操作.range(0,3) "==" [0,1,2]
并且缺少"3 1"边缘,缺少"2 0"边缘,这是最后一个边缘.矩阵从0开始计数.
马蒂亚斯拥有它;您不需要edgeCount - 1,因为该range函数不包含迭代中的最终值。
您还可以执行其他几项操作来清理代码:
with员是打开文件的首选,因为它会自动为您关闭文件find和手动切片,split已经做了你想要的。range仅使用结束值进行调用,0开始是隐式的。有了所有这些变化:
with open('graph.txt', 'r') as graph:
node_count, edge_count = (int(n) for n in graph.readline().split())
matrix = [[0]*node_count for _ in range(node_count)]
for i in range(edge_count):
src, dst = (int(n) for n in graph.readline().split())
matrix[src][dst] = 1
print matrix
# [[0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 0, 0, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
277 次 |
| 最近记录: |