Python graph


Introduction

A graph in mathematics and computer science consists of “nodes” which may or may not be connected with one another. Connections between nodes are called edges.  A graph can be directed (arrows) or undirected. The edges could represent distance or weight.

graph mathematics

default graph (left), directed graph (right)

Python does not have a graph data type. To use graphs we can either use a module or implement it ourselves:

  • implement graphs ourselves
  • networkx module

Graph in Python

A directed graph can be defined as:

#!/usr/bin/env python
 
graph = {'A': ['B', 'C'],
         'B': ['C', 'A'],
         'C': ['D'],
         'D': ['A']}
 
print(graph)

Graphs using networkx

The networkx software module has support for creating, manipulating  graphs.

#!/usr/bin/env python
import networkx as nx
 
G=nx.Graph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","A")
 
print("Nodes: " + str(G.nodes()))
print("Edges: " + str(G.edges()))

Result:

Nodes: ['A', 'C', 'B']
Edges: [('A', 'C'), ('A', 'B'), ('C', 'B')]


3 thoughts on “Python graph

  1. Al-Amin - December 28, 2015

    import networkx as nx
    dosen’t work syntaxerror

    1. Frank - December 28, 2015

      Install the networkx module using: pip install networkx

      1. Carl Wainwright - August 29, 2016

        You will need to install virtualenv on OSX otherwise you will have trouble installing networkx module.