Can be used to represent lot's of stuff!
class Graph:
def __init__(self):
# Initial graph has nothing connected
self.adjacency = {}
def connect(self, vertex1, vertex2, weight=None):
# If the vertex has never been added to the graph, add it, but with no connects
if vertex1 not in self.adjacency:
self.adjacency[vertex1] = {}
# now connect the edges, by adding a vertex2 key to the vertex1 adjanceny map with value of the weight
self.adjacency[vertex1][vertex2] = weight
# if the graph is not directed, you'll also need a self.adjacency[vertex2][vertex1] = weight
def is_vertex(self, vertex):
return vertex in self.adjacency
def are_connected(self, vertex1, vertex2):
return self.is_vertex(vertex1) and vertex2 in self.adjacency[vertex1]
def weight(self, vertex1, vertex2):
return self.adjacency[vertex1][vertex2]
def neighbors(self, vertex1):
return self.adjacency[vertex1].keys()
# Test Code
G = Graph()
G.connect('A', 'B')
G.connect('A', 'C')
G.connect('B', 'C')
G.connect('C', 'D')
print(G.are_connected('A', 'B')) # True
print(G.are_connected('B', 'A')) # False, because the graph is directed!
print(G.are_connected('A', 'C')) # False, because there is no direct connection
print(G.neighbors('A')) # ['C', 'B']
Hashtable<String, Hashtable<String, String>>to store adjacency