0

I have encounter a very strange python problem, code below. I input a grid (2d array) [[7, 8, 9], [4, 5, 6], [1, 2, 3]]

from typing import List

def test(
        height: int,
        width: int,
        grid: List[List[int]]):

    print(grid)

    refList = [[0]*width]*height
    for h in range (0, height):
        for w in range (0, width):
            if h == 0 and w == 0:
                refList[h][w] = grid[h][w]
            elif(h < 1):
                refList[h][w] = refList[h][w-1] +grid[h][w]
            elif(w < 1):
                refList[h][w] = refList[h-1][w] + grid[h][w]
            else:
                refList[h][w] = grid[h][w] + max(refList[h-1][w], refList[h][w-1])
            print(refList[h][w])
    
    print(refList)

grid = [[7,8,9],[4,5,6],[1,2,3]]
test(3,3,grid)

I expect the output [[7,15,24],[11,20,30],[12,22,33]]. as you can see below, the print function inside the loop prints the correct answers, but after the loop finished and print the whole list, it gave me this [[12, 22, 33], [12, 22, 33], [12, 22, 33]] - basically all top row.

[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
7
15
24
11
20
30
12
22
33
[[12, 22, 33], [12, 22, 33], [12, 22, 33]]

What is going on here and how can I fix this?

1 Answer 1

2

You are experimenting an issue due to shallow copies. You should use:

refList = [[0 for i in range(width)] for j in range(height)]

in replacement of your current initialisation line:

refList = [[0]*width]*height

Indeed, this last line create an array of reference to the same line-based array internally ([[0]*width]). You can check that easily use the following code:

refList = [[0]*3]*3
print(refList[0] is refList[1])  # Print True
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.