90일차 - Matrix Expansion

--------------------------------------------Failed My Solution -----------------------------------------


new = [[0 for col in range(matrix.__len__() + n)] for row in range(matrix.__len__() + n)]
print(new)
for i in range(0, matrix.__len__() + n):
    if i < matrix.__len__():
        for j in range(0, matrix[i].__len__() + n):
            if j < matrix.__len__():
                new[i][j] = matrix[i][j]
            else:
                new[i][j] = sum(new[i][0:j])
    else:
        for j in range(0, matrix.__len__() + n):
            print(i, j)

-------------------------------------------- Other's Solution -----------------------------------------
import numpy as np


def expansion(matrix, n):
    a = np.array(matrix)

    while n > 0:
        a = np.append(a, [np.sum(a, axis=0)], axis=0)  # Append row
        col = np.array([np.sum(a, axis=1)])  # Calculate column
        a = np.concatenate((a, col.T), axis=1)  # Concatenate column
        a[-1][-1] = np.trace(a) - a[-1][-1]  # Correct last diagonal element
        n -= 1

    return a.tolist()

좋은 웹페이지 즐겨찾기