0

Why creating a matrix multiplying first by rows and then by columns like this;

class Blíster:
def __init__(self,row,columns):
    self.nfil=row
    self.ncol=columns
    self.__matriu=[[True]*columns]*row

def __getitem__(self,i):
    return self.__matriu[i[0]][i[1]]

def __setitem__(self,i,p):
    self.__matriu[i[0]][i[1]]= p      

Is different than appending rows, like this:

class Blíster:
def __init__(self, rows, columns) :
    self.nfil = rows
    self.ncol = columns
    self.cavitats = []
    for i in range(rows) :
        self.cavitats.append([True]*columns)
        
def __getitem__(self, pos) :
    return self.cavitats[pos[0]][pos[1]]

def __setitem__(self, pos, p) :
    self.cavitats[pos[0]][pos[1]] = p

When i try

b = blíster.Blíster(3, 6)
b[1, 2] = False
b[2, 5] = False
b[2, 4] = False
b[1, 3] = False
c = 0
for i in range(3) :
   for j in range(6) :
      if b[i, j] :
          c = c + 1

With the first way of creating a matrix, i get that c=6 So it assigns False to more than 4 times in the matrix, and I don't know why. If anyone could explain it to me, I would be so grateful :D

Doing it with the second way, i got c=14, the good answer.

Emi Gurei
  • 3
  • 2

1 Answers1

0

In your first implementation each row is the same in memory, so changing the value in one row changes it in all of them.

>>> myList = [[True]*2]*3
>>> myList
[[True, True], [True, True], [True, True]]
>>> myList[0][0] = False
>>> myList
[[False, True], [False, True], [False, True]]

The mechanics of this behavior are explained in answer to this question.

Moarram
  • 66
  • 4