from typing import List def mutatingInsertRowAndCol(L: List[List[int]], row: int, col: int, val: int): """Inserts a row and column into a matrix.""" L.insert(row, [val] * len(L[0])) for i in range(len(L)): L[i].insert(col, val) def nonmutatingInsertRowAndCol( L: List[List[int]], row: int, col: int, val: int ) -> List[List[int]]: """Inserts a row and column into a matrix without mutating the original matrix.""" new_list = [[v for v in l] for l in L] new_list.insert(row, [val] * len(new_list[0])) for i in range(len(new_list)): new_list[i].insert(col, val) return new_list def testMutatingInsertRowAndCol(): print("Testing mutatingInsertRowAndCol()...", end="") L = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] mutatingInsertRowAndCol(L, 1, 2, 42) assert L == [ [1, 2, 42, 3, 4], [42, 42, 42, 42, 42], [5, 6, 42, 7, 8], [9, 10, 42, 11, 12], ] L = [[1, 2, 3], [4, 5, 6]] mutatingInsertRowAndCol(L, 0, 0, 5) assert L == [[5, 5, 5, 5], [5, 1, 2, 3], [5, 4, 5, 6]] L = [[1, 2, 3], [4, 5, 6]] mutatingInsertRowAndCol(L, 1, 3, 5) assert L == [[1, 2, 3, 5], [5, 5, 5, 5], [4, 5, 6, 5]] def testNonmutatingInsertRowAndCol(): print("Testing nonmutatingInsertRowAndCol()...", end="") L = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] assert nonmutatingInsertRowAndCol(L, 1, 2, 42) == [ [1, 2, 42, 3, 4], [42, 42, 42, 42, 42], [5, 6, 42, 7, 8], [9, 10, 42, 11, 12], ] L = [[1, 2, 3], [4, 5, 6]] assert nonmutatingInsertRowAndCol(L, 0, 0, 5) == [ [5, 5, 5, 5], [5, 1, 2, 3], [5, 4, 5, 6], ] L = [[1, 2, 3], [4, 5, 6]] assert nonmutatingInsertRowAndCol(L, 1, 3, 5) == [ [1, 2, 3, 5], [5, 5, 5, 5], [4, 5, 6, 5], ] # Verify that the function is non-mutating L = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] nonmutatingInsertRowAndCol(L, 1, 2, 42) assert L == [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print("Passed!") def main(): testMutatingInsertRowAndCol() testNonmutatingInsertRowAndCol() main()