SwadhyAI Notes

All Python notes

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.