Python TypeError:不可损坏的类型:“节点”
我有这段代码,可以找到源和目标之间最短、最快的路径Python TypeError:不可损坏的类型:“节点”,python,depth-first-search,Python,Depth First Search,我有这段代码,可以找到源和目标之间最短、最快的路径 class Node(object): def __init__(self, ID, name, power, generation): """ Creates Node Object Requires: (id = int), (name = string), (power = int), (generation = int) """ self.id =
class Node(object):
def __init__(self, ID, name, power, generation):
"""
Creates Node Object
Requires: (id = int), (name = string), (power = int), (generation = int)
"""
self.id = ID
self.name = name
self.power = power
self.generation = generation
def getId(self):
"""
Gets id atribute.
"""
return self.id
def getName(self):
"""
Get name atribute.
"""
return self.name
def getPower(self):
"""
Get power atribute.
"""
return self.power
def getGeneration(self):
"""
Get generation atribute.
"""
return self.generation
def allInfo(self):
'''
Gives a representation of each node atribiutes
'''
return "ID: " + str(self.id) + " | NAME: " + self.name + " | POWER: " + str(self.power) + " | GENERATION: " + str(self.generation)
def __str__(self):
return self.name
def __eq__(self, other):
'''
Sets node if equal to other id if is an instance
'''
if isinstance(other, Node):
return self.id == other.id
return False```
类Digraphobject:
def __init__(self):
"""
Nodes is a list of the nodes in the graph.
Edges is a dict mapping each node to a list of its children.
"""
self.nodes = []
self.edges = {}
def addNode(self, node):
"""
Adds the nodes.
"""
if node in self.nodes:
raise ValueError('Duplicate node')
else:
self.nodes.append(node)
self.edges[node] = []
def主参数:
'
接收参数作为shell中给定文件的主函数,以关联程序操作
要求:
args是指定要读取的多个文件的较早版本
确保:
创建带有站点时间连接的输出文件
"
您的节点是自定义节点类的实例: 但Python需要它们的关键是: 如果一个对象的哈希值在其生存期内从未改变,则该对象是可哈希的。它需要一个_哈希_;方法,并且可以与它需要一个_eq _;方法的其他对象进行比较。比较相等的可散列对象必须具有相同的散列值 哈希性使对象可用作字典键和集合成员,因为这些数据结构在内部使用哈希值 Python的所有不可变内置对象都是可散列的;不支持列表或字典等可变容器。默认情况下,作为用户定义类实例的对象是可散列的。它们除了自身之外都比较不相等,并且它们的散列值是从它们的id派生的
因此,如果您想将节点用作字典键,则必须为它们实现和使用魔术方法。错误似乎附加在代码中,您在relayStations.py第113行中没有显示这些代码。我担心这个错误是显式的,您试图使用可变类型作为字典中的键。如果需要进一步的帮助,您必须显示Node类。但是我有一个eq方法,您不仅需要uu eq u方法,还需要u hash u方法。
stations = []
conns = []
file_in = open(args[1], "r")
for line in file_in:
if (line[0] != "#"):
station_info = line.split(", ")
stations.append(Node(int(station_info[0]),
station_info[1],
int(station_info[2]),
int(station_info[3])))
conns.append(line.split("(")[1].split(", "))
g = Digraph()
for station in stations:
g.addNode(station)
aux = 0
for station in stations:
for s in conns[aux]:
# por \r\n em mac
pos = (int(s.replace("\n", ""))) - 1
g.addEdge(Edge(station, stations[int(pos)]))
aux += 1
file_in.close()
file_in = open(args[2], "r")
maxTest = len(file_in.readlines())
file_in.close()
file_in = open(args[2], "r")
file_out = open(args[3], "w")
count = 0
for line in file_in:
line = line.replace("\n", "")
stationNames = line.split(" ")
stop = False
stationA = findStation(stations, stationNames[0])
if stationA == None:
file_out.write(stationNames[0] + " out of the network\n")
stop = True
stationB = findStation(stations, stationNames[1])
if stationB == None:
file_out.write(stationNames[1] + " out of the network\n")
stop = True
if stationA == stationB:
file_out.write("Trying to connect same station (" + stationA.getName() + ", " + stationB.getName() + ")\n")
stop = True
if not stop:
file_out.write(str(search(g, stationA, stationB)) + "\n")
count += 1
percentage = round(count * 100 / maxTest, 1)
sys.stdout.write("\r Progress: " + str(percentage) + "% | ")
sys.stdout.write("Tested: " + str(count) + " of " + str(maxTest) + " connections!")
sys.stdout.flush()
sys.stdout.write("\n")
file_in.close()
file_out.close()
but i'm getting this error
C:\Users\André Ramos\Desktop\Project\Project\relayStationsGroup12>python
relayStations.py inputFile1.txt inputFile2.txt out.txt
########################## Relay Stations ############################
RelayStations is running...
Traceback (most recent call last):
File "relayStations.py", line 339, in <module>
main(sys.argv)
File "relayStations.py", line 270, in main
g.addNode(station)
File "relayStations.py", line 113, in addNode
self.edges[node] = ()
TypeError: unhashable type: 'Node'
Node(int(station_info[0]),
station_info[1],
int(station_info[2]),
int(station_info[3]))