我是Python的初学者,并且已经面临这个问题一段时间了。任何纠正问题的建议都是有价值的。 下面是使用Dijkstra算法找到最短路径的代码。我有成本矩阵和源作为输入。
def dijkstra(cost_matrix,source):
n = 20
dist = [0 for row in range(20)]
visited = [0 for row in range(20)]
for j in range(20):
visited[j] = "False"
visited[source] = "True"
for i in range(20):
dist[i] = cost_matrix[source][i]
prev_min = source
for k in range(20):
minimum = min(dist)
minimum2 = min(minimum,n)
for i in range(20):
if dist[i] > (cost_matrix[prev_min][minimum2] + cost_matrix[minimum2][i]):
dist[i] = cost_matrix[prev_min][minimum2] + cost_matrix[minimum2][i]
visited[minimum2] = "True"
prev_min = minimum2
return dist
计算cost_matrix的代码
def matrix():
k = 30
b_ij = [[0 for row in range(20)] for col in range(20)]
a_ij = [[0 for row in range(20)] for col in range(20)]
cost_matrix = [[0 for row in range(20)] for col in range(20)]
for i in range(20):
for j in range(20):
rand = random.randint(0,8)
b_ij[i][j] = rand
b_ij[j][i] = rand
while(k > 0):
rand1 = random.randint(0,19)
rand2 = random.randint(0,19)
a_ij[rand1][rand2] = 200
a_ij[rand2][rand1] = 200
k = k - 1
for i in range(20):
for j in range(20):
if a_ij[i][j] != 200:
rand = random.randint(0,8)
a_ij[i][j] = rand
a_ij[j][i] = rand
for i in range(len(a_ij)):
for j in range(len(b_ij[0])):
for k in range(len(b_ij)):
cost_matrix[i][j] += a_ij[i][k] * b_ij [k][j]
错误讯息:
Traceback (most recent call last):
File "ass1.py", line 60, in <module>
print(dijkstra(cost_matrix, 1))
File "ass1.py", line 45, in dijkstra
dist[i] = cost_matrix[source][i]
TypeError: 'NoneType' object is not subscriptable
答案 0 :(得分:2)
您仍然没有在创建cost_matrix
的位置发布实际代码。您发布了矩阵函数的代码,但没有发布使用矩阵函数的代码。
但是,看起来问题是你的matrix
函数没有返回任何内容。它只是创建一个矩阵并抛弃它。您需要在该函数的末尾添加return cost_matrix
。
答案 1 :(得分:0)
cost_matrix或cost_matrix [source]的值为None,但它应该是一个列表。
在行前打印它们:
dist[i] = cost_matrix[source][i]
找出问题所在。
顺便说一句,你应该把numpy用于这类东西。