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?