CMU Coding Bootcamp
1from typing import List
2
3
4def mutatingInsertRowAndCol(L: List[List[int]], row: int, col: int, val: int):
5 """Inserts a row and column into a matrix."""
6 L.insert(row, [val] * len(L[0]))
7 for i in range(len(L)):
8 L[i].insert(col, val)
9
10
11def nonmutatingInsertRowAndCol(
12 L: List[List[int]], row: int, col: int, val: int
13) -> List[List[int]]:
14 """Inserts a row and column into a matrix without mutating the original matrix."""
15 new_list = [[v for v in l] for l in L]
16
17 new_list.insert(row, [val] * len(new_list[0]))
18 for i in range(len(new_list)):
19 new_list[i].insert(col, val)
20
21 return new_list
22
23
24def testMutatingInsertRowAndCol():
25 print("Testing mutatingInsertRowAndCol()...", end="")
26 L = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
27 mutatingInsertRowAndCol(L, 1, 2, 42)
28 assert L == [
29 [1, 2, 42, 3, 4],
30 [42, 42, 42, 42, 42],
31 [5, 6, 42, 7, 8],
32 [9, 10, 42, 11, 12],
33 ]
34
35 L = [[1, 2, 3], [4, 5, 6]]
36 mutatingInsertRowAndCol(L, 0, 0, 5)
37 assert L == [[5, 5, 5, 5], [5, 1, 2, 3], [5, 4, 5, 6]]
38
39 L = [[1, 2, 3], [4, 5, 6]]
40 mutatingInsertRowAndCol(L, 1, 3, 5)
41 assert L == [[1, 2, 3, 5], [5, 5, 5, 5], [4, 5, 6, 5]]
42
43
44def testNonmutatingInsertRowAndCol():
45 print("Testing nonmutatingInsertRowAndCol()...", end="")
46 L = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
47 assert nonmutatingInsertRowAndCol(L, 1, 2, 42) == [
48 [1, 2, 42, 3, 4],
49 [42, 42, 42, 42, 42],
50 [5, 6, 42, 7, 8],
51 [9, 10, 42, 11, 12],
52 ]
53
54 L = [[1, 2, 3], [4, 5, 6]]
55 assert nonmutatingInsertRowAndCol(L, 0, 0, 5) == [
56 [5, 5, 5, 5],
57 [5, 1, 2, 3],
58 [5, 4, 5, 6],
59 ]
60
61 L = [[1, 2, 3], [4, 5, 6]]
62 assert nonmutatingInsertRowAndCol(L, 1, 3, 5) == [
63 [1, 2, 3, 5],
64 [5, 5, 5, 5],
65 [4, 5, 6, 5],
66 ]
67
68 # Verify that the function is non-mutating
69 L = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
70 nonmutatingInsertRowAndCol(L, 1, 2, 42)
71 assert L == [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
72 print("Passed!")
73
74
75def main():
76 testMutatingInsertRowAndCol()
77 testNonmutatingInsertRowAndCol()
78
79
80main()