You are on page 1of 5

Advertisements

REPORT THIS AD

Discovering Python & R

— my journey as a worker bee in quant finance

Adjacency Matrix

Implementing Undirected Graphs in Python


(https://pythonandr.com/2016/07/28/implementin
g-undirected-graphs-in-python/)
July 28, 2016July 28, 2016 Anirudh Technical Adjacency List, Adjacency Matrix,
Algorithms, Code Snippets, example, Graphs, Math, Python
There are 2 popular ways of representing an undirected graph.

Adjacency List
Each list describes the set of neighbors of a vertex in the graph.

Adjacency Matrix
The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph.
Here’s (https://gist.github.com/anirudhjayaraman/1f74eb656c3dd85ff440fb9f9267f70a) an
implementation of the above in Python:

1 class Vertex:
2 def __init__(self, vertex):
3 self.name = vertex
4 self.neighbors = []
5
6 def add_neighbor(self, neighbor):
7 if isinstance(neighbor, Vertex):
8 if neighbor.name not in self.neighbors:
9 self.neighbors.append(neighbor.name)
10 neighbor.neighbors.append(self.name)
11 self.neighbors = sorted(self.neighbors)
12 neighbor.neighbors = sorted(neighbor.neighbors)
13 else:
14 return False
15
16 def add_neighbors(self, neighbors):
17 for neighbor in neighbors:
18 if isinstance(neighbor, Vertex):
19 if neighbor.name not in self.neighbors:
20 self.neighbors.append(neighbor.name)
21 neighbor.neighbors.append(self.name)
22 self.neighbors = sorted(self.neighbors)
23 neighbor.neighbors = sorted(neighbor.neighbors)
24 else:
25 return False
26
27 def __repr__(self):
28 return str(self.neighbors)
29
30 class Graph:
31 def __init__(self):
32 self.vertices = {}
33
34 def add_vertex(self, vertex):
35 if isinstance(vertex, Vertex):
36 self.vertices[vertex.name] = vertex.neighbors
37
38
39 def add_vertices(self, vertices):
40 for vertex in vertices:
41 if isinstance(vertex, Vertex):
42 self.vertices[vertex.name] = vertex.neighbors
43
44 def add_edge(self, vertex_from, vertex_to):
45 if isinstance(vertex_from, Vertex) and isinstance(vertex_to, Vertex):
46 vertex_from.add_neighbor(vertex_to)
47 if isinstance(vertex_from, Vertex) and isinstance(vertex_to, Vertex):
48 self.vertices[vertex_from.name] = vertex_from.neighbors
49 self.vertices[vertex_to.name] = vertex_to.neighbors
50
51 def add_edges(self, edges):
52 for edge in edges:
53 self.add_edge(edge[0],edge[1])
54
55 def adjacencyList(self):
56 if len(self.vertices) >= 1:
57 return [str(key) + ":" + str(self.vertices[key]) for key in self.vertices.keys()]
58 else:
59 return dict()
60
61 def adjacencyMatrix(self):
62 if len(self.vertices) >= 1:
63 self.vertex_names = sorted(g.vertices.keys())
64 self.vertex_indices = dict(zip(self.vertex_names, range(len(self.vertex_names))))
65 import numpy as np
66 self.adjacency_matrix = np.zeros(shape=(len(self.vertices),len(self.vertices)))
67 for i in range(len(self.vertex_names)):
68 for j in range(i, len(self.vertices)):
69 for el in g.vertices[self.vertex_names[i]]:
70 j = g.vertex_indices[el]
71 self.adjacency_matrix[i,j] = 1
72 return self.adjacency_matrix
73 else:
74 return dict()
75
76 def graph(g):
77 """ Function to print a graph as adjacency list and adjacency matrix. """
78 return str(g.adjacencyList()) + '\n' + '\n' + str(g.adjacencyMatrix())
79
80 ######################################################################
81
82 a = Vertex('A')
83 b = Vertex('B')
84 c = Vertex('C')
85 d = Vertex('D')
86 e = Vertex('E')
87
88 a.add_neighbors([b,c,e])
89 b.add_neighbors([a,c])
90 c.add_neighbors([b,d,a,e])
91 d.add_neighbor(c)
92 e.add_neighbors([a,c])
93
94 g = Graph()
95 print graph(g)
96 print
97 g.add_vertices([a,b,c,d,e])
98 g.add_edge(b,d)
99 print graph(g)
view raw graphUndirected.py hosted with by GitHub
Output:

1 {}
2
3 {}
4
5
6 ["A:['B', 'C', 'E']", "C:['A', 'B', 'D', 'E']", "B:['A', 'C', 'D']", "E:['A', 'C']", "D:['B', 'C']"]
7
8 [[ 0. 1. 1. 0. 1.]
9 [ 1. 0. 1. 1. 0.]
10 [ 1. 1. 0. 1. 1.]
11 [ 0. 1. 1. 0. 0.]
12 [ 1. 0. 1. 0. 0.]]
view raw graphUndirected_output.txt hosted with by GitHub
Advertisements

REPORT THIS AD

REPORT THIS AD
Leave a comment
Advertisements

REPORT THIS AD

Blog at WordPress.com. (https://wordpress.com/?ref=footer_blog)

You might also like