1

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.

DrDoggo
  • 13
  • 2
  • You're only iterating through `dp[0]` – 2pichar Jan 19 '22 at 18:20
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – DjaouadNM Jan 19 '22 at 18:24

1 Answers1

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.

Eli Harold
  • 2,280
  • 1
  • 3
  • 22