Python snippet showing weird behaviour
Here's the code for reference:-
temp = [0 for _ in range(5)]
dp = [temp for _ in range(len(wt)+1)]
for i in range(len(wt)):
for j in range(len(dp[0])):
print("outside inner loop if statement:",dp,i,j)
if j-wt[i] >=0:
print(i,j)
dp[i][j] = "y"
print("inside inner loop if statement dp:", dp)
Here's the relevant output:-
outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 0
outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 1
outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 2
outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 3
outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 4
0 4
inside inner loop if statement dp: [[0, 0, 0, 0, 'y'], [0, 0, 0, 0, 'y'], [0, 0, 0, 0, 'y'], [0, 0, 0, 0, 'y']]
The moment the flow goes in the if block when i=0 and j=4, every fourth column changes to 'y' even though the ideal behavior should be dp[0][4] = 'y'
Thanks in advance.
Solution 1:
Since temp
is stored in dp
multiple times you are changing all occurrences of temp
when you do dp[0][4] = 'y'
so it changes all rows to have 'y'.
Instead you need:
dp = [[0 for _ in range(5)] for _ in range(len(wt)+1)]
for i in range(len(wt)):
for j in range(len(dp[0])):
print("outside inner loop if statement:",dp,i,j)
if j-wt[i] >=0:
print(i,j)
dp[i][j] = "y"
print("inside inner loop if statement dp:", dp)
Because dp = [[0 for _ in range(5)] for _ in range(len(wt)+1)]
will re evaluate [0 for _ in range(5)]
each time as a different list.