I was trying to substitute a number (60) for an initialized two-dimensional array (dp) due to a problem with dynamic programming.
[Problem] Atcoder EDPC C-Vacation (https://atcoder.jp/contests/dp/tasks/dp_c)
I wrote the following code.
dp=[[0,0,0]]*5
print(dp)
#output[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
a=[10,40,70]
dp[0]=a
print(dp)
#output[[10,40,70],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
#Below is the code in question#######
dp[0][1]=60
print(dp)
#output[[10,40,70],[0,60,0],[0,60,0],[0,60,0],[0,60,0]]
I really wanted to substitute 60 only for dp [0] [1]. (Less than)
print(dp)
#output[[10,40,70],[0,60,0],[0,0,0],[0,0,0],[0,0,0]]
If the list is initialized as follows, all the element lists will be created as the same object. (Less than)
#Bad example 1
dp=[[0,0,0]]*5
#Bad example 2
dp=[[0]*3]*5
If you initialize the list with " Comprehension notation </ b>" as shown below, all can be created as different objects.
dp=[[0]*3 for i in range(5)]
dp[0][1]=60
print(dp)
#output[[10,40,70],[0,60,0],[0,0,0],[0,0,0],[0,0,0]]
numpy makes it easy
import numpy as np
dp=np.zeros((5,3))
dp[0,1]=60
print(dp)
#Output array([[ 0., 0., 0.],[ 0., 60., 0.],[ 0., 0., 0.],[ 0., 0., 0.],[ 0., 0., 0.]])
If you want to initialize a multidimensional array with list type, use comprehension notation. However, it is easier to initialize with numpy.
https://note.nkmk.me/python-list-initialize/
Recommended Posts