I have some simple code that represents a graph using a square boolean matrix where rows/columns are nodes and true represents an undirected link between two nodes. I am initializing this matrix with False values and then setting the value to True where a link exists.
I believe the way I am initializing the list is causing a single bool instance to be referenced by each cell in a given row. The result is that if I set any cell to True all the other cells in that row also become True.
How should I be initializing my square matrix so that all values are false but none are shared by reference with other cells?
import sys
class Graph(object):
def __init__(self, nodeCount, links):
self.matrix = [[False] * nodeCount] * nodeCount
for l in links:
self.matrix[l[0]][l[1]] = True
def __str__(self):
s = " "
for i in range(len(self.matrix)):
s += str(i) + " "
s += "\n"
for r in range(len(self.matrix)):
s += str(r) + " "
for c in range(len(self.matrix)):
s += str(self.matrix[c][r])[0] + " "
s += "\n"
return s
g = Graph(5, [(2,3)])
print g
Also, on GIST