I was using dynamic programming to implement the Matrix_Chain Problem, i.e. figure out the minimum number of multiplications to be done in matrix multiplication via parenthesizing. My code was not working until I changed the way of initializing list m
. Could someone explain why, even when m = [[0]*n]*n
and m = [[0 for x in range(n)] for x in range(n)]
make seemingly identical list, m = [[0]*n]*n
will results in matrix entry not being correctly updated to the minimum cost?
I made list m = [[0]*5]*5
and printed
for a in m:
print(a)
I made list n = [[0 for x in range(5)] for x in range(5)]
and also printed in the same way. The results are identical.
import sys
def Matrix_Chain (p, n):
m = [[0]*n]*n #problematic step
for i in range (1,n):
m[i][i] =0
for L in range(2, n):
for i in range(1,n-L+1):
j = i + L -1
m[i][j] = sys.maxsize
for k in range (i, j):
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if q < m[i][j]:
m[i][j] = q
return m[1][n-1]
For argument p = [1,2,3,4]
and n = 4
, I expect to see 18
, the minimum number of multiplications. However, the m = [[0]*n]*n
way will return 9223372036854775807
, which is the sys.maxsize
. The m = [[0 for x in range(n)] for x in range(n)]
way returns the correct answer 18
.