i have python code expected output matrix same size of input matrix. output value @ [i,j] should equal twice sum of d[i-1,j] , d[i,j] , add ouput @ instance [i-1,j] it. code follows
import numpy np d=((2,3,5,6),(4,6,7,9),(8,4,7,3),(1,7,3,9),(5,8,2,6)) d=np.matrix(d) r,c = np.shape(d) temp=[] y=[] y.append([0,0,0,0]) in range (r-1): ro = d[i:i+2,:] #fetch 2 rows @ time i.e. , i+1 j in range (c): col = ro[:,j] #fetch 1 column of row v1 = int(col[0]) v2 = int(col[1]) x = (v1+v2)*2+int(y[i][j]) temp.append(x) y.append(temp) y = np.matrix(y) print y expected output is
[[0,0,0,0] [12,18,24,30] [36,38,52,54] [54,60,72,78] [66,90,82,108]] but instead get:
[[[0, 0, 0, 0] [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60] [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60] [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60] [12, 18, 24, 30, 36, 38, 52, 54, 30, 40, 44, 54, 24, 48, 34, 60]]] where error in code?
you have reset temp accumulator each iteration of outer loop. code look:
... in range (r-1): ro = d[i:i+2,:] #fetch 2 rows @ time i.e. , i+1 temp = [] # <------------- j in range (c): ... the unexpected output got original code because of way python lists work: when append object python list, reference object stored, not copy of object. after loop has finished, list y looks like:
[reference [0,0,0,0], reference list created @ line 7, reference list created @ line 7, reference list created @ line 7, reference list created @ line 7] so last 4 references same single object!
Comments
Post a Comment