Python Matrix Multiplication Function Algorithm Question!

Asked 2 years ago, Updated 2 years ago, 28 views

I'm asking you a question because I don't understand the multiplication algorithm of matrix in Programmer's Algorithm Exercise level 2. First of all, the code I made

   def productMatrix(A, B):
       answer = len(A)*[list(range(len(B[0])))]  #Form of the multiplication result matrix.

       for i in range (len(A): row of #A,
           for j in range (len(B[0]): Has a column value of #B.
               B_column_j=[]
               For row in B: Create column j of #B
                   B_column_j.append(row[j])
               answer[i][j]=sum(A[i][k]*B_column_j[k] for k in range(len(A[i])))
                            #(column i of A)*(column j of B) dot product 
               print('answer[{}][{}]={}'.format(i,j,answer[i][j]))
               print(answer)
return answer

# Below is the code for testing.
a = [ [ 1, 2 ], [ 2, 3 ]];
b = [[ 3, 4], [5, 6]];
print("Results: {}".format(productMatrix(a,b)));

If you print it out, answer[0][0]=13
[[13, 1], [13, 1]]
answer[0][1]=16
[[13, 16], [13, 16]]
answer[1][0]=21
[[21, 16], [21, 16]]
answer[1][1]=26
[[21, 26], [21, 26]]
Result: [[21, 26], [21, 26]]

Each answer[i][j] is correct, but I don't know why the answer comes out like that. Please explain.

python programmer

2022-09-22 19:39

1 Answers

answer = len(A)*[list(range(len(B[0]))]] has a problem.

See Related questions !


2022-09-22 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.