Graph¶

Generally graphs are represented as a list of edges; they can be used as undirected or directed graphs

In [1]:
edges = [(0, 1), (1, 3), (0, 3), (2, 1)] # without edge values
edges = [(0, 1, 1), (1, 3, 2), (0, 3, 6), (2, 1, 1)] # with edges values


A class can be used to store the information

In [ ]:
class Graph:
    def __init__(self, edges):
        self.edges = edges



Another solution is to use a dict to store for a node i all its neighbours¶

In an object dictionnary

In [ ]:
from collections import defaultdict

# directed Graph
graph = defaultdict(list)
for i, j, w in edges:
    graph[i].append((j, w))
    
# undirected Graph
graph = defaultdict(list)
for i, j, w in edges:
    graph[i].append((j, w))
    graph[j].append((i, w))


Or a class can be used

In [ ]:
from collections import defaultdict

# directed Graph
class Graph:
    def __init__(self, edges):
        self.graph = defaultdict(list)
        for i, j, w in edges:
            self.graph[i].append((j, w))
            
# undirected Graph
class Graph:
    def __init__(self, edges):
        self.graph = defaultdict(list)
        for i, j, w in edges:
            self.graph[i].append((j, w))
            self.graph[j].append((i, w))