1

I have attached my python code below where I am facing some difficulty in initializing list with some values please take a look at it:-

array = [1, 2, 3, 3]
value = 6
dp = [[-1] * (value + 1)] * (len(array) + 1) 



for i in range(len(array) + 1):
    for j in range(value + 1):
        if i == 0 and j > 0:
            dp[i][j] = 0
        elif i >= 0 and j == 0:
            dp[i][j] = 1
        else:
            dp[i][j] = -1


for i in dp:
    for j in i:
        print(j,end = " ")
    print()

The output which I am getting is :-

1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1

The output which I am expecting is:-

1  0  0  0  0  0  0
1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1
1 -1 -1 -1 -1 -1 -1

can you guys please figure out where I am going wrong as I am learning to use python stuffs.

juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152
Varun
  • 13
  • 6

1 Answers1

0

* (len(array) + 1) creates copies of the [[-1] * (value + 1)] list, so every change is effecting all the sublists. Use a for loop to create the sublists instead

dp = [[-1] * (value + 1) for _ in range(len(array) + 1)]
Guy
  • 40,130
  • 10
  • 33
  • 74