물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Square Matrix Multiplication

BEstyle 2022. 11. 8. 14:43

DESCRIPTION:

Write a function that accepts two square (NxN) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given.

How to multiply two square matrices:

We are given two matrices, A and B, of size 2x2 (note: tests are not limited to 2x2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell [0][0] of matrix C, you need to compute: A[0][0] * B[0][0] + A[0][1] * B[1][0].

More general: To fill in cell [n][m] of matrix C, you need to first multiply the elements in the nth row of matrix A by the elements in the mth column of matrix B, then take the sum of all those products. This will give you the value for cell [m][n] in matrix C.

Example

  A         B          C
|1 2|  x  |3 2|  =  | 5 4|
|3 2|     |1 1|     |11 8|

def matrix_mult(a, b):
    alist=[]
    l=len(a)
    for i in range(l):
        temp=[]
        for j in range(l):
            temp.append(getVal(i,j,a,b))
        alist.append(temp)
    print(alist)
    return alist       

    return

def getVal(x,y,a,b):
    l=len(a)
    ans=0
    for i in range(l):
        ans+=a[x][i]*b[i][y]
    return ans

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Simple Frequency Sort  (0) 2022.11.10
Binary to Text (ASCII) Conversion  (0) 2022.11.09
Twisted Sum  (0) 2022.11.08
Number Zoo Patrol  (0) 2022.11.07
Loose Change  (0) 2022.11.07