Thursday, April 15, 2010

Python graphs adjacency matrix to adjacency list

I've been playing with it, and here's the code I came with (posting it here so that it doesn't get lost afterwards, as it usually happens.


matrix = [
[0,1,0],
[1,0,1],
[0,1,0]]

def adjmatrix_to_adjlist(graph_as_matrix=matrix):
adj_list = {}
for (index,nodes) in enumerate(graph_as_matrix):
adj_list[index+1]=([verteces+1 for verteces in range(len(nodes)) if nodes[verteces]==1])
return adj_list

graph_as_list = adjmatrix_to_adjlist()

No comments:

Categories

code (15) fun (2) linux (31) miscellaneous (9) music (8)

About me

I'm Adrian and this is my blog. Here I usually write about technical stuff (mostly about Linux).
Copyright: BY-NC_SA, Author: aeter