gpt4 book ai didi

python - 执行 Union-Find,得到 TypeError : 'builtin_function_or_method' object is not subscriptable

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:36:31 28 4
gpt4 key购买 nike

我正在尝试使用路径压缩算法实现快速联合,但出于某种原因,我在测试时遇到了 TypeError: 'builtin_function_or_method' object is not subscriptable。我觉得一切都很好。这是代码;感谢您的帮助。

这是完整的错误,后面是代码:

Traceback (most recent call last):
File "quick-find.py", line 75, in <module>
a.union(7,9)
File "quick-find.py", line 56, in union
node2_root = self.root(node2)
File "quick-find.py", line 47, in root
self.id[node] = self.id[id[node]]
TypeError: 'builtin_function_or_method' object is not subscriptable
class weightedQuickUnion:
def __init__(self, n):
self.id = list(range(n))
self.size = list([1]) * n

def root( self, node ):
# Improved to make every node point to its parent
# This improvement makes it weightedQuickUnionWithPathCompression
while ( node != self.id[node]):
self.id[node] = self.id[id[node]]
node = self.id[node]
return node

def connected(self, node1, node2):
return self.id[node1] == self.id[node2]

def union(self, node1, node2):
node1_root = self.root(node1)
node2_root = self.root(node2)
if node1_root == node2_root:
return
if (self.size[node1_root] < self.size[node2_root]):
self.id[node1_root] = node2_root
self.size[node2_root] += self.size[node1_root]
else:
self.id[node2_root] = node1_root
self.size[node1_root] += self.size[node2_root]

a = weightedQuickUnion(10)
print(a.id)
print(a.size)
print(a.connected(3,4))
a.union(3,4)
a.union(1,3)
a.union(6,9)
print(a.id)
print(a.size)
a.union(7,9) # <-- this line throws an exception and I can't figure out why.
a.union(8,9)

最佳答案

感谢@jasonharper 指出我删除了“ self ”。来自以下行:

self.id[node] = self.id[id[node]]

相反,它应该是这样的:

self.id[node] = self.id[self.id[node]]

关于python - 执行 Union-Find,得到 TypeError : 'builtin_function_or_method' object is not subscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917353/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com