Search code examples
pythonlistdeep-copy

How to give a list variable to two class variable?


I used "copy" to get two class variables. But when the latter function modifies the value of one of two variables, the other variable changes. How can I generate two independent variables?

Can't import other package like numpy to solve it. Thanks guys.

Question 200 in Leetcode, number of islands

input_list = [  [0, 1, 1, 1, 0],
                [0, 1, 0, 1, 1], 
                [1, 1, 0, 0, 1], 
                [0, 0, 1, 0, 1]]

class Solution():
    def __init__(self, input_list_ori):
        self.island_count = 0
        self.input_list = input_list_ori.copy()
        # self.input_list_ori = [[0 for j in range(len(self.input_list[0]))]for i in range(len(self.input_list))]
        self.input_list_ori = self.input_list.copy()
        self.dirs = [[-1, 0], [0, 1], [0, -1], [1, 0]]

    def find_connect_one(self):
        assert(len(self.input_list) > 0)
        for i_row in range(len(self.input_list[0])):
            for i_col in range(len(self.input_list)):
                if self.input_list[i_row][i_col] == 1:
                    self.island_count += 1
                    self.dfs(i_row, i_col)
        return self.island_count, self.input_list_ori

    def dfs(self, i_row, i_col):
        self.input_list[i_row][i_col] = 0
        self.input_list_ori[i_row][i_col] = self.island_count

        for dir in self.dirs:
            new_i_row = i_row+dir[0]
            new_i_col = i_col+dir[1]
            if new_i_row >= 0 and new_i_col >= 0 and new_i_row < len(self.input_list) and new_i_col < len(self.input_list[0]):
                if self.input_list[new_i_row][new_i_col] == 1:
                    self.dfs(new_i_row, new_i_col)

solution = Solution(input_list)
print(len(input_list))
island_count, input_list_ori = solution.find_connect_one()
print(island_count)

def dfs(self, i_row, i_col):
    self.input_list[i_row][i_col] = 0
    self.input_list_ori[i_row][i_col] = self.island_count

I hope to get different value in these two list. Although I have generated them by "copy" operator, they always influence each other.


Solution

  • You should use copy.deepcopy.

    More explanations from the documentation:

    • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

    • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

    Your copy is creating a new list with reference to the internal list. Thus when you are modifying internal list, there are for the both list, self.input_list, and self.input_list_ori.