7.3b Matrices in Python labs
Source: Lab ideas from Computational Physics (Landau, Páez, Bordeianu), §7.3–7.3.3. Rewritten as original drills. Continues 7.3 Matrices in Python.
These drills implement what NumPy gives you for free (+, dot, solve) using plain Python lists — so build them yourself with list/list-of-lists, not numpy (the exercise sandbox has no third-party packages anyway). This reinforces exactly why a real array type is worth having. Stubs fail until filled in.
Labs
Plain Python lists concatenate under + ([1,2,3]+[1,2,3] == [1,2,3,1,2,3]), unlike a NumPy array. Implement true elementwise addition of two equal-length lists yourself.
Input: first line list a (space-separated numbers), second line list b. Print the elementwise sum, space-separated, as integers (assume integer inputs).
Write-ups
Using “concatenate”, “elementwise”, and “list”, explain:
What does + do to two plain Python lists, and how does that differ from NumPy array addition?
Minimum 3 words. Your answer must include: “concatenate”, “elementwise”, “list”.
Meet the writing requirements, then you can open the model answer.
Explorers
# matrix_ref.py — matmul and Gaussian-elimination solve (original sketch)
def matmul(A, B):
n = len(A)
return [[sum(A[i][k] * B[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
def solve(A, b):
n = len(b)
A = [row[:] for row in A]
b = b[:]
for i in range(n):
piv = A[i][i]
for j in range(i + 1, n):
f = A[j][i] / piv
for k in range(n):
A[j][k] -= f * A[i][k]
b[j] -= f * b[i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = b[i]
for k in range(i + 1, n):
s -= A[i][k] * x[k]
x[i] = s / A[i][i]
return x
Next: 7.4 Tests before use.