I wrote this function in python to do matrix multiplication but for some reason it's not working as intended. The code looks fine to me but python seems to be filling in all lists at position y in my matrix and I don't understand why its doing this.
def maal(N, M):
a = []
b = []
for i in range(len(N)):
a.append(0)
for j in range(len(M[0])):
b.append(a)
for x in range(len(N)):
for y in range(len(M[0])):
for z in range(len(M)):
b[x][y] += N[x][z] * M[z][y]
return b
print(maal([[5, 4, 32], [5, 6, 74]], [[1, 2], [4, 5], [7, 8]]))
#solution is b = [[245, 286],[547,632]]
The output I'm getting is [[792, 918], [792, 918]]
because it's filling both list at once.
Can anyone help me out?
You are appending the same list, meaning the same object in memory, len(M[0])
times to b
in the line b.append(a)
. b.append(a)
does not copy a.
Change that line to b.append(a[:])
or b.append(a.copy())
.
Simplified demo of what's going on in your code:
>>> a = [0, 0, 0]
>>> b = []
>>> b.append(a)
>>> b.append(a)
>>> a[-1] = 1
>>> a
[0, 0, 1]
>>> b
[[0, 0, 1], [0, 0, 1]]
>>> b[0] is a
True
>>> b[1] is a
True