dacoda007
dacoda007

Reputation: 63

python edge list to adjacency matrix

Given an edge list, I need to convert the list to an adjacency matrix in Python. I am very, very close, but I cannot figure out what I am doing incorrectly. Where is my thinking incorrect?

E= [[0, 0], [0, 1], [1, 0], [1, 1]]

nmax = max(E)
nmax2 =max(nmax)

m = []
for i in range(nmax2+1):
    row = []
    for j in range(nmax2+1):
         if [i,j]== E[i]:
               row.append(1)
         else:
               row.append(0)
    m.append(row)

 print(m)

I would expect the result to be: 1 1 1 1

But my code produces: 1 0 0 0

Upvotes: 3

Views: 12340

Answers (2)

kcp
kcp

Reputation: 33

i blv below is cleaner and does the job

    E= [[0, 0], [0, 1], [1, 0], [1, 1]]
    size = max(max(E))+1
    r = [[0 for i in range(size)] for j in range(size)]
    for row,col in E:
        r[row][col] = 1
    print(r)    

Upvotes: 0

modesitt
modesitt

Reputation: 7210

As the comment suggests, you are only checking edges for as many rows as you have in your adjacency matrix, so you fail to reach many edges in the general case. Consider the following instead:

E = [[0, 0], [0, 1], [1, 0], [1, 1]]

# nodes must be numbers in a sequential range starting at 0 - so this is the
# number of nodes. you can assert this is the case as well if desired 
size = len(set([n for e in E for n in e])) 
# make an empty adjacency list  
adjacency = [[0]*size for _ in range(size)]
# populate the list for each edge
for sink, source in E:
    adjacency[sink][source] = 1

>>> print(adjacency)
>>> [[1, 1], [1, 1]]

If you want to be brief at the cost of clarity:

adjacency = [[1 if [i, j] in set(map(tuple, E)) else 0 for j in range(size)] for i in range(size)]

size representing the number of nodes - as before.

Upvotes: 3

Related Questions