Hello I understand the concepts of adjacency list and matrix but I am confused as to how to implement them in Python:
An algorithm to achieve the following two examples achieve but without knowing the input from the start as they hard code it in their examples:
For adjacency list:
a, b, c, d, e, f, g, h = range(8)
N = [
{b:2, c:1, d:3, e:9, f:4}, # a
{c:4, e:3}, # b
{d:8}, # c
{e:7}, # d
{f:5}, # e
{c:2, g:2, h:2}, # f
{f:1, h:6}, # g
{f:9, g:8} # h
]
For adjacency matrix:
a, b, c, d, e, f, g, h = range(8)
_ = float('inf')
# a b c d e f g h
W = [[0,2,1,3,9,4,_,_], # a
[_,0,4,_,3,_,_,_], # b
[_,_,0,8,_,_,_,_], # c
[_,_,_,0,7,_,_,_], # d
[_,_,_,_,0,5,_,_], # e
[_,_,2,_,_,0,2,2], # f
[_,_,_,_,_,1,0,6], # g
[_,_,_,_,_,9,8,0]] # h
Again any help will be much appreciated, Thank you!
An adjacency matrix occupies n2/8 byte space (one bit per entry). An adjacency list occupies 8e space, where e is the number of edges (32bit computer). So with these numbers (still 32-bit specific) the breakpoint lands at 1/64.
An adjacency list represents a graph as an array of linked lists. The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex.
An adjacency matrix is a way of representing a graph as a matrix of booleans (0's and 1's). A finite graph can be represented in the form of a square matrix on a computer, where the boolean value of the matrix indicates if there is a direct path between two vertices.
In graph theory and computer science, an adjacency list is a collection of unordered lists used to represent a finite graph. Each unordered list within an adjacency list describes the set of neighbors of a particular vertex in the graph.
Assuming:
edges = [('a', 'b'), ('a', 'b'), ('a', 'c')]
Here's some code for the matrix:
from collections import defaultdict
matrix = defaultdict(int)
for edge in edges:
matrix[edge] += 1
print matrix['a', 'b']
2
And for the "list":
from collections import defaultdict
adj_list = defaultdict(lambda: defaultdict(lambda: 0))
for start, end in edges:
adj_list[start][end] += 1
print adj_list['a']
{'c': 1, 'b': 2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With