0

I have noticed that probability_matrix seems to become adapted_given_board despite never being assigned it.

def build_probability_matrix(self):
    r = 0
    p = -1
    adapted_given_board = self.probability_matrix
    print(self.game.board.given_board)
    for i in range(len(self.game.board.given_board)-1):
        p += 1
        if self.game.board.given_board[i] == '\n':
            r += 1
            p = -1
        else:
            adapted_given_board[r][p] = self.game.board.given_board[i]
    print(adapted_given_board)
kosist
  • 2,868
  • 2
  • 17
  • 30
  • 4
    Because it _is_ the same list. `adapted_given_board = self.probability_matrix` does not create a copy, it creates another name referring to the same object in memory. Any changes to either name will be reflected across both – roganjosh Oct 30 '19 at 19:51
  • 2
    `adapted_given_board = self.probability_matrix.copy()` – JacobIRR Oct 30 '19 at 19:54
  • I wanna say that [this](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) is the canonical but it's not because I think there's one without a list comp... I just can't think of it – roganjosh Oct 30 '19 at 19:54

1 Answers1

0

This assignment:

adapted_given_board = self.probability_matrix

is a reference, not a copy. That is, you're creating a new name for self.probability_matrix, not a new list that has a copy of the contents.

So when you do:

adapted_given_board[r][p] = self.game.board.given_board[i]

it's the exact same as if you'd done:

self.probability_matrix[r][p] = self.game.board.given_board[i]

Be careful about trying to use copy to fix this, since you're working with two-dimensional lists; you might end up just pushing the problem down one level. There is such a thing as deepcopy, but here's one idea for a very minimal fix that just allocates new entries in the matrix before you assign to them:

def build_probability_matrix(self):
    r = 0
    p = -1
    adapted_given_board = [[]]  # start with one row that has zero cells
    print(self.game.board.given_board)
    for i in range(len(self.game.board.given_board)-1):
        p += 1
        adapted_given_board[r].append(None)  # add a cell
        if self.game.board.given_board[i] == '\n':
            r += 1
            adapted_given_board.append([])   # add a row
            p = -1
        else:
            adapted_given_board[r][p] = self.game.board.given_board[i]
    print(adapted_given_board)

Or you could simply append your new elements rather than assigning them by index...

def build_probability_matrix(self):
    adapted_given_board = [[]]        
    print(self.game.board.given_board)
    for element in self.game.board.given_board:
        if element == '\n':
            adapted_given_board.append([])
        else:
            adapted_given_board[-1].append(element)
    print(adapted_given_board)
Samwise
  • 68,105
  • 3
  • 30
  • 44