Python Tutorial: Graphs 🎯

beginner
13 min

Python Tutorial: Graphs 🎯

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! 🚀

What are Graphs? 📝

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.

Types of Graphs 💡

  1. Directed Graph (Digraph): A graph where edges have directions.
  2. Undirected Graph: A graph where edges do not have directions.

Creating a Graph in Python 💡

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:

bash
pip install networkx

Now, let's create a simple undirected graph:

python
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)

Basic Operations on Graphs 💡

  • Creating a Directed Graph: Replace nx.Graph() with nx.DiGraph() to create a directed graph.
  • Adding Edges: Use add_edge(node1, node2) to add an edge between two nodes.
  • Number of Nodes: Use number_of_nodes() to find the number of nodes in a graph.
  • Number of Edges: Use number_of_edges() to find the number of edges in a graph.

Real-world Example: Social Network 📝

Let's create a simple social network where we represent users as nodes and friendships as edges:

python
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')

Visualizing Graphs 💡

networkx provides functionality for visualizing graphs using various formats like png, pdf, and more.

python
import matplotlib.pyplot as plt nx.draw(G, with_labels=True) plt.show()

This will create a graph visualization with node labels.

Graph Algorithms 💡

Python's networkx library offers several built-in graph algorithms like:

  • Breadth-First Search (BFS)
  • Depth-First Search (DFS)
  • Dijkstra's Algorithm
  • Floyd-Warshall Algorithm

We'll explore these algorithms in future lessons.

Quiz Time 💡

Quick Quiz
Question 1 of 1

What is a Graph in Python?

Keep learning, and happy coding! 🤖🚀