I’m building a graph class represented as a dict. The graph class is used to perform path finding on a large 2D grid matrix. The nodes are stored as keys and the neighbour nodes are stored as values.
This works nice for fast path searches but I also need to get specific nodes out of the dict determined by their x and y coordinates.
class Node(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Graph(dict):
def get_node_at(self, x, y):
for node in self:
if node.x == x and node.y == y:
return node
def set_neighbours(self):
pass
graph = Graph()
# build a 2d matrix of nodes
for x in range(10):
for y in range(10):
graph[Node(x,y)] = []
# set the neighbour nodes for each node
graph.set_neighbours()
mynode = graph.get_node_at(6,6) # will later be executed quite often
Is there a way to optimize the graph class so the get_node_at method performs better on a large grid?
add an index to
Graphwhich would look like{(x,y):node}. this would require implementing__setitem__to add theNodeto the index, and remove it if anotherNodealready exists and__delitem__would also remove theNodefrom the index. this would allowget_node_at(self, x, y)to just doreturn self.index[(x,y)].