Python Graph đ¸ī¸
Graph Data Structure
A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges.
⨠Display Graph Vertices
To display the graph vertices we simple iterate through the keys of the graph dictionary.
python
class Graph:
def __init__(self, gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
graph_elements = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = Graph(graph_elements)
print(g.getVertices())đŽ Interactive Graph Demo
âšī¸ Ready to build a Graph!
a
b
c
d
e
đ Display Graph Edges
Edges can be a bit tricky as we have to represent the connection between two vertices.
python
class Graph:
def __init__(self, gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def edges(self):
return self.findedges()
def findedges(self):
edgename = []
for vrtx in self.gdict:
for nxtvrtx in self.gdict[vrtx]:
if {nxtvrtx, vrtx} not in edgename:
edgename.append({vrtx, nxtvrtx})
return edgename
graph_elements = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = Graph(graph_elements)
print(g.edges())đĄ Did You Know?
Graphs are used to model pairwise relations between objects, such as social networks, road maps, and computer networks.