A graph consists of a set of edges and nodes that can or cannot be linked to one another. Networks such as social networks and the Internet are represented as graphs.
Graphs are a versatile and widely used data structure in computer science, representing entities (nodes or vertices) and their relationships (edges). This chapter provides a comprehensive introduction to graphs in Python, including their structure, representations, and common operations.
A graph G is defined as a pair G = (V, E), where:
Directed vs. Undirected:
Weighted vs. Unweighted:
Cyclic vs. Acyclic:
An adjacency list represents a graph as a dictionary where each key is a vertex, and the value is a list of its neighbors.
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
This representation is efficient for sparse graphs, where the number of edges is much smaller than V2.
An adjacency matrix is a 2D array where the element at position (i,j) indicates whether an edge exists between the vertex i and j.
# Adjacency Matrix for the graph above
# Vertices: A, B, C, D, E, F
matrix = [
[0, 1, 1, 0, 0, 0], # A
[1, 0, 0, 1, 1, 0], # B
[1, 0, 0, 0, 0, 1], # C
[0, 1, 0, 0, 0, 0], # D
[0, 1, 0, 0, 0, 1], # E
[0, 0, 1, 0, 1, 0] # F
]
This is efficient for dense graphs, where the number of edges approaches V2.
An edge list is a simple list of all edges, represented as pairs or tuples of vertices.
edges = [
('A', 'B'), ('A', 'C'), ('B', 'D'),
('B', 'E'), ('C', 'F'), ('E', 'F')
]
Edge lists are space-efficient and easy to construct for dynamic graphs.
The most common implementation uses a dictionary for the adjacency list.
class Graph:
def __init__(self):
self.graph = {}
def add_vertex(self, vertex):
if vertex not in self.graph:
self.graph[vertex] = []
def add_edge(self, vertex1, vertex2):
if vertex1 in self.graph and vertex2 in self.graph:
self.graph[vertex1].append(vertex2)
self.graph[vertex2].append(vertex1) # Undirected graph
def display(self):
for vertex, edges in self.graph.items():
print(f"{vertex} -> {', '.join(edges)}")
g = Graph()
g.add_vertex('A')
g.add_vertex('B')
g.add_vertex('C')
g.add_edge('A', 'B')
g.add_edge('A', 'C')
g.display()
To display the graph vertices we simply find the keys of the graph dictionary. We use the keys() method.
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = []
self.gdict = gdict
# Get the keys of the dictionary
def getVertices(self):
return list(self.gdict.keys())
# Create the dictionary with graph elements
graph_elements = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
g = graph(graph_elements)
print(g.getVertices())
Output
Finding the graph edges is a little trickier than the vertices as we have to find each of the pairs of vertices which have an edge in between them.
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def edges(self):
return self.findedges()
# Find the distinct list of edges
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
# Create the dictionary with graph elements
graph_elements = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
g = graph(graph_elements)
print(g.edges())
Output
There are the following use cases of the Graph:
A graph consists of a set of edges and nodes that can or cannot be linked to one another. Networks such as social networks and the Internet are represented as graphs.
Graphs are a versatile and widely used data structure in computer science, representing entities (nodes or vertices) and their relationships (edges). This chapter provides a comprehensive introduction to graphs in Python, including their structure, representations, and common operations.
A graph G is defined as a pair G = (V, E), where:
Directed vs. Undirected:
Weighted vs. Unweighted:
Cyclic vs. Acyclic:
An adjacency list represents a graph as a dictionary where each key is a vertex, and the value is a list of its neighbors.
pythongraph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] }
This representation is efficient for sparse graphs, where the number of edges is much smaller than V2.
An adjacency matrix is a 2D array where the element at position (i,j) indicates whether an edge exists between the vertex i and j.
python# Adjacency Matrix for the graph above # Vertices: A, B, C, D, E, F matrix = [ [0, 1, 1, 0, 0, 0], # A [1, 0, 0, 1, 1, 0], # B [1, 0, 0, 0, 0, 1], # C [0, 1, 0, 0, 0, 0], # D [0, 1, 0, 0, 0, 1], # E [0, 0, 1, 0, 1, 0] # F ]
This is efficient for dense graphs, where the number of edges approaches V2.
An edge list is a simple list of all edges, represented as pairs or tuples of vertices.
pythonedges = [ ('A', 'B'), ('A', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'F'), ('E', 'F') ]
Edge lists are space-efficient and easy to construct for dynamic graphs.
The most common implementation uses a dictionary for the adjacency list.
pythonclass Graph: def __init__(self): self.graph = {} def add_vertex(self, vertex): if vertex not in self.graph: self.graph[vertex] = [] def add_edge(self, vertex1, vertex2): if vertex1 in self.graph and vertex2 in self.graph: self.graph[vertex1].append(vertex2) self.graph[vertex2].append(vertex1) # Undirected graph def display(self): for vertex, edges in self.graph.items(): print(f"{vertex} -> {', '.join(edges)}") g = Graph() g.add_vertex('A') g.add_vertex('B') g.add_vertex('C') g.add_edge('A', 'B') g.add_edge('A', 'C') g.display()
To display the graph vertices we simply find the keys of the graph dictionary. We use the keys() method.
pythonclass graph: def __init__(self,gdict=None): if gdict is None: gdict = [] self.gdict = gdict # Get the keys of the dictionary def getVertices(self): return list(self.gdict.keys()) # Create the dictionary with graph elements graph_elements = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } g = graph(graph_elements) print(g.getVertices())
Output
Finding the graph edges is a little trickier than the vertices as we have to find each of the pairs of vertices which have an edge in between them.
pythonclass graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def edges(self): return self.findedges() # Find the distinct list of edges 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 # Create the dictionary with graph elements graph_elements = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } g = graph(graph_elements) print(g.edges())
Output
There are the following use cases of the Graph:
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is ₹5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from ₹3,000 - ₹1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved