-1

This is my Node class,

class Node:
    def __init__(self, id, value):
        self.id = id
        self.value = value
        self.neighbors = set()

    def add_edge(self, node):
        self.neighbors.add(node)

    def get_adjacent_vertices(self):
        return sorted(list(self.neighbors))

    def __eq__(self, other):
        return self.id == other.id

    def __lt__(self, other):
        return self.id < other.id

    def __gt__(self, other):
        return self.id > other.id

    def __ge__(self, other):
        return self.id >= other.id

    def __le__(self, other):
        return self.id <= other.id

And this is the graph object,

class Graph:
    def __init__(self, directed=False):
        self.vertices = 0
        self.directed = directed
        self.vertex_map = {}

    def add_edge(self, v1, v2, weight=1):
        if v1 in self.vertex_map:
            V1 = self.vertex_map[v1]
        else:
            self.vertices += 1
            V1 = Node(self.vertices, v1)
            self.vertex_map[v1] = V1
        if v2 in self.vertex_map:
            V2 = self.vertex_map[v2]
        else:
            self.vertices += 1
            V2 = Node(self.vertices, v2)
            self.vertex_map[v2] = V2
        if V1 != V2:
            V1.add_edge(V2)
            if not self.directed:
                V2.add_edge(V1)
        else:
            raise GraphError("Cannot add node to itself!")

This is my calling code,

if __name__ == '__main__':
    graph = Graph(directed=True)
    graph.add_edge('A', 'B')
    graph.add_edge('A', 'C')
    graph.add_edge('B', 'D')
    graph.add_edge('D', 'E')
    print(graph)

This throws up the following error,

TypeError: unhashable type: 'Node'

I can fix this by changing the neighbors to a list, but my question is since I've already defined the hashing logic for a Node, how can I continue to use a set to store it's neighbors.

Melissa Stewart
  • 3,483
  • 11
  • 49
  • 88

1 Answers1

0

Well I think you can use the id for each element which will be unique to every element. And instead of set you can also use a defaultdict which will be used to store all the adjacent elements of a vertex.

from collections import defaultdict adjacent_node_list = defaultdict(lambda:[])

def add_edge(self,u,v):
    if v not in d[u]:
        d[u].append(v)

If the graph is undirected then you will have to add u to d[v] as well For more inputs pls specify what you are actually trying to do

Nikhil Rathore
  • 170
  • 2
  • 14