0 votes
1 view
in Data Science by (18.3k points)
edited by

Below is the code

n = 4

m = 4

figures = [1,2,2]

def almostTetris(n, m, figures):

    grid = [[0] * m] * n

    def shape1(count):

        for i in range(n):

            for j in range(m):

                if grid[i][j] == 0:

                    print(grid[i][j])

                    print(grid[1][0])

                    print(grid[2][0])

                    print(grid[3][0])

                    grid[i][j] = count

                    print(grid[i][j])

                    print(grid[1][0])

                    print(grid[2][0])

                    print(grid[3][0])

                    return

    def shape2(count):

        for i in range(n):

            for j in range(m - 2):

                if grid[i][j] == 0 and grid[i][j + 1] == 0 and grid[i][j + 2] == 0:

                    grid[i][j] = grid[i][j + 1] = grid[i][j + 2] = count

                    return

    for i in range(len(figures)):

        if figures[i] == 1:

            shape1(i + 1)

        elif figures[i] == 2:

            shape2(i + 1)

    

    return grid

print(almostTetris(n, m, figures))

This is what I got as my output:

0

0

0

0

1

1

1

1

[[1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2]]

My question is how does the grid[i][j] = count convert all the numbers in my first column to 1 (the value of count)? I thought both i and j are 0, only my first element would change to 1.

1 Answer

0 votes
by (36.8k points)

The problem is present in the below line

grid=[[0]*m]*n

Because it doesn't create the nxm grid of 0s, it copies that object: [[0]*m] n times to create this 2d array. Hence if you mutate one of the values in this object, other n object instances get edited too. Try the below lines:

grid = [[0]*m for _ in range(n)]

 If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...