3

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

1
  • 1
    E[i] goes maximum up to E[1] because i goes only from 0 to 1. So you never reach [1, 0] and [1, 1] Commented Mar 30, 2019 at 22:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)    

1 Comment

in an adjacency matrix, the dimmension is always square - this is not correct generally

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.