Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjacency Matrix not populating correctly python

Tags:

python

I tried to implement a simple adjacency matrix to keep track of which nodes are connected to which nodes in an undirected graph. However, my adjacency matrix keeps screwing up by changing entire columns instead of individual cells. Here's my code:

def setup_adj_matrix(size, edges):
    # initialize matrix with zeros
    adj_matrix = [[0] * size] * size
    # edges is a list of tuples, representing 2 nodes connected by an edge
    for edge in edges:
        v1 = edge[0]
        v2 = edge[1]
        adj_matrix[v1][v2] = 1
        adj_matrix[v2][v1] = 1
    for row in adj_matrix:
        print row

for a graph with 3 nodes (0, 1, 2) and edges [(0,1),(0,2),(1,2)], I should be getting

[[0,1,1],
 [1,0,1],
 [1,1,0]]

However, I am getting all 1's. Any ideas where the problem might be?

like image 301
JP_smasher Avatar asked Sep 01 '26 14:09

JP_smasher


2 Answers

The multiplication operator with a list and an int returns multiple references to the same list, not multiple copies. Your array contains the same object nine times.

You can create the correct array with a double list comprehension:

def init_matrix(x, y):
    return [[[0] for i in range(x)] for j in range(y)]
like image 168
llb Avatar answered Sep 03 '26 05:09

llb


The lists are all shallow copies of each other, so when you edit one you're actually editing each row. Try this for initializing the matrix:

adj_matrix = [[0] * size for i in range(size)]
like image 20
thegrinner Avatar answered Sep 03 '26 05:09

thegrinner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!