TypeError:列表索引必须是整数或切片,而不是类型



我正在Python中使用邻接矩阵实现广度优先搜索算法。

出于某种原因,我遇到了一个错误,我不知道为什么会出现。我的代码是下一个:

import numpy as np
# Matrix creation.
n = int(input("Enter n, the dimension of the adjacency matrix: "))
M = np.zeros(shape=(n, n))
# Matrix filling.
print("Insert the matrix elements, representing the edges joining nodes: ")
for i in range(n):
for j in range(n):
M[i][j] = int(input("M[{}][{}]= ".format(i, j)))
print("n The matrix is: n {} n".format(M))

print("Insert two nodes to compute the shortest path between them. Remember that the nodes are labed from zero to {}: n".format(n))
a = int(input("First node: "))
b = int(input("Second node: "))
# Queue of visiting nodes. The first element is the starting node.
q = [a]
# Array for visited nodes. The element corresponding to the starting node is marked as visited.
vis = [False] * n
vis[a] = True
# Array of the previous node for the ith node. It starts empty, and of size n.
prev = [int] * n
# Loop to fill the prev array for all nodes. It runs until the queue is empty.
while q:
# The ith node is the queue front.
node = q[0]
adj = M[node]
q.pop(0)
# Checks all connections from the ith node.
for i in range(n):
if adj[i] != 0:
if not vis[i]:
# If a connection is found, it's added to the queue, marked as visited and saved in memory in prev.
q.append(i)
vis[i] = True
prev[i] = node
# Backwards path.
bw = []

#
i = b
while i is not None:
bw.append(i)
i = prev[i]
# Path array creation
w = len(bw)
path = [int] * w
# Filling of the path, from the information of the backwards one.
for i in range(w):
aux = bw[i]
j = w-1-i
path[j] = aux
if path[0] == a:
print("nThe shortest path between the node {} and the node {} is {},n".format(a, b, path))
else:
print("nThere's not a path between {} and {} :(n".format(a, b))

错误是下一个:

i = prev[i]
TypeError: list indices must be integers or slices, not type

如果prev[i]是一个整数数组,为什么我不能使i = prev[i]??

我试着用i = int(prev[i])打字,但没用。现在我不知道该怎么办。我们将不胜感激。

我认为您的问题在于:

prev = [int] * n

您正在创建一个包含int类型本身的列表。应该是[0]*n或类似的。实际上,我不知道你为什么不做一个空列表:prev = []

最新更新