TypeError:无法散列的类型:“ Node”

时间:2019-05-27 15:41:45

标签: 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 = 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```

Digraph类(对象):

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 main(args):     '''     接收args作为shell中给定文件以启动程序操作的主要功能     要求:     args对于要读取的多个文件而言较旧     确保:     使用工作站时间连接创建输出文件     '''

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'

1 个答案:

答案 0 :(得分:0)

您的节点是自定义Node类的实例:

Node(int(station_info[0]),
     station_info[1],
     int(station_info[2]),
     int(station_info[3]))

但是Python dictionaries需要其密钥为hashable

  

如果对象的哈希值在其生命周期内始终不变(需要使用__hash__()方法,并且可以与其他对象进行比较(需要使用__eq__()方法),则该对象是可哈希的。比较相等的可哈希对象必须具有相同的哈希值。

     

可哈希性使对象可用作字典键和set成员,因为这些数据结构在内部使用哈希值。

     

所有Python不变的内置对象都是可哈希的;可变容器(例如列表或字典)不是。默认情况下,作为用户定义类实例的对象是可哈希的。它们都比较不相等(除了它们本身),并且其哈希值是从其id()派生的。

因此,如果要将节点用作字典键,则必须为其实现__hash____eq__魔术方法。