Welcome to the Graphs lesson of our Python Tutorial! In this comprehensive guide, we'll delve into the world of Graphs, a fundamental data structure used in various real-world applications like social networks, road networks, and world wide web. Let's embark on this exciting journey! 🚀
A Graph is a non-linear data structure consisting of vertices (also known as nodes) and edges (connections between vertices). Graphs are incredibly versatile and can represent pairwise relations between objects.
Python provides several libraries for working with Graphs, but in this tutorial, we'll be using the networkx library. To get started, you'll need to install it using pip:
pip install networkxNow, let's create a simple undirected graph:
import networkx as nx
G = nx.Graph()
# Add vertices
G.add_nodes_from([1, 2, 3, 4, 5])
# Add edges
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edge(2, 4)
G.add_edge(3, 4)
G.add_edge(3, 5)nx.Graph() with nx.DiGraph() to create a directed graph.add_edge(node1, node2) to add an edge between two nodes.number_of_nodes() to find the number of nodes in a graph.number_of_edges() to find the number of edges in a graph.Let's create a simple social network where we represent users as nodes and friendships as edges:
G = nx.Graph()
# Add nodes (users)
G.add_nodes_from(['Alice', 'Bob', 'Charlie', 'David', 'Eve'])
# Add edges (friendships)
G.add_edge('Alice', 'Bob')
G.add_edge('Alice', 'Charlie')
G.add_edge('Bob', 'Charlie')
G.add_edge('Bob', 'David')
G.add_edge('Charlie', 'Eve')networkx provides functionality for visualizing graphs using various formats like png, pdf, and more.
import matplotlib.pyplot as plt
nx.draw(G, with_labels=True)
plt.show()This will create a graph visualization with node labels.
Python's networkx library offers several built-in graph algorithms like:
We'll explore these algorithms in future lessons.
What is a Graph in Python?
Keep learning, and happy coding! 🤖🚀