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

发布于 2025-01-18 21:47:14 字数 2231 浏览 0 评论 0原文

我正在使用邻接矩阵在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

为什么我不能制作i = prev [i]如果prev [i]整数数组?

我尝试使用i = int(prev [i])打字i,但它不起作用。 现在我不知道该怎么办。 一些帮助将不胜感激。

I'm implementing a breadth-first search algorithm in Python using adjacency matrices.

By some reason, I'm getting an error I don't why it's appearing.
My code is the next:

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))

The error is the next:

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

Why can't I make i = prev[i] if prev[i] an array of integers??

I tried to typecast i with i = int(prev[i]) but it didn't work.
And now I don't know what to do.
Some help will be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳絮泡泡 2025-01-25 21:47:14

我认为您的问题是在线:

prev = [int] * n

您正在创建一个包含INT类型的列表。应该是[0]*N或类似的东西。
实际上,我不确定为什么您不做空列表:prev = []

I think your problem is in the line:

prev = [int] * n

You're creating a list containing the type int itself. Should be [0]*n or something similar.
I'm actually not sure why you're not making an empty list: prev = []

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文