๊ธ€ ์ž‘์„ฑ์ž: ํƒ์‹œ ์šด์ „์‚ฌ
๋ฐ˜์‘ํ˜•

๐Ÿ‘ฉโ€๐Ÿซ ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ ๋ฌธ์ œ ํ’€์–ด๋ณด๊ธฐ


๐Ÿ˜ƒ ๋‚˜์˜ ์ฝ”๋“œ

def solution(arr1, arr2):
    answer = []
    for idx1 in range(len(arr1)):
        row = []
        for idx2 in range(len(arr2[0])):
            tmp = 0
            for idx3 in range(len(arr1[0])):
                tmp += arr1[idx1][idx3] * arr2[idx3][idx2]
            row.append(tmp)
        answer.append(row)
    return answer

์ œํ•œ ์กฐ๊ฑด์—์„œ ๊ณฑํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฐ์—ด๋งŒ ์ฃผ์–ด์ง„๋‹ค๊ณ  ํ–ˆ์œผ๋‹ˆ, ๋‘ ๋ฐฐ์—ด์„ A X B, B X C๋กœ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋‘ ํ–‰๋ ฌ์˜ ๊ณฑ์œผ๋กœ ๋‚˜์˜จ ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋Š” A X C๊ฐ€ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๊ฒฐ๊ณผ ๋ฐฐ์—ด์˜ ์™ผ์ชฝ ์œ„๋ถ€ํ„ฐ ์˜ค๋ฅธ์ชฝ ์•„๋ž˜๊นŒ์ง€ ๋งŒ๋“ค์–ด ๋‚˜๊ฐ€๋ฉด ๋˜๋Š” ์‰ฌ์šด ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

def solution(arr1, arr2):
    A = len(arr1)
    B = len(arr1[0])
    C = len(arr2[0])
    return [[sum([arr1[idx1][idx3] * arr2[idx3][idx2] for idx3 in range(B)]) for idx2 in range(C)] for idx1 in range(A)]

์ œ๊ฐ€ ๋งŒ๋“  ์ฝ”๋“œ์ •๋„๋กœ ์งœ๋„ ๋Œ์•„๊ฐ€๊ธด ํ•˜์ง€๋งŒ, for loop๋ฅผ ์ด์šฉํ•˜์—ฌ list๋ฅผ ์ข€ ๋” ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ๋Š” ๋ฐฉ๋ฒ•์ธ Python์˜ list comprehension์„ ์ด์šฉํ•ด์„œ ์ข€ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๋งŒ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

def productMatrix(A, B):
    return [[sum(a*b for a, b in zip(A_row,B_col)) for B_col in zip(*B)] for A_row in A]

ํ•˜์ง€๋งŒ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๋งŒ๋“ค ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. arr2 ์—ด์— ๋Œ€ํ•œ ๋ฐฐ์—ด์„ zip(*B)๋ฅผ ์ด์šฉํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๊ฐ„๋‹จํ•ด์ง‘๋‹ˆ๋‹ค.

Written with StackEdit.


๋ฐ˜์‘ํ˜•