0

Below is my 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))

and this is what I got printed out:

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 grid[i][j] = count convert all numbers in the first column to 1 (the value of count)? I thought that because i and j are all 0, only the first element would change to 1.

martineau
  • 119,623
  • 25
  • 170
  • 301
jginso7
  • 95
  • 7
  • 1
    Problem is here: `grid = [[0] * m] * n` as it creates a bunch of references to the same list instead of new lists as you expect. Use list comprehension instead. – norok2 Oct 11 '20 at 00:58
  • wow Thanks a lot... I was just so unable to understand this... – jginso7 Oct 11 '20 at 01:03

1 Answers1

0

When I was first learning python I struggled with this too. The problem is in this line

grid=[[0]*m]*n

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

grid = [[0]*m for _ in range(n)]
feverdreme
  • 467
  • 4
  • 12