Doing linear algebra homework reminds me why I love NumPy so much. Instead of doing a 2-page homework assignment and then finding out at the end that something is wrong, I can check at every step. For example, to reduce a matrix A to the identity, using only elementary matrices:
#!/usr/bin/env python2
from itertools import chain
import numpy as np
# Given by the assignment
a = np.matrix([
[-1, 1, 1],
[3, 1, 0],
[-2, 1, 1]
])
# Add to e as I find them
e = []
e.append(np.matrix([
[1, 0, -1],
[0, 1, 0],
[0, 0, 1]
]))
e.append(np.matrix([
[1, 0, 0],
[0, 1, 1],
[0, 0, 1]
]))
e.append(np.matrix([
[1, 0, 0],
[-1, 1, 0],
[0, 0, 1]
]))
e.append(np.matrix([
[1, 0, 0],
[0, 1, 0],
[2, 0, 1]
]))
e.append(np.matrix([
[1, 0, 0],
[0, 1, -2],
[0, 0, 1]
]))
e.append(np.matrix([
[1, 0, 0],
[0, 0, 1],
[0, 1, 0]
]))
e.append(np.matrix([
[1, 0, 0],
[0, 1, 1],
[0, 0, 1]
]))
e.append(np.matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, -1]
]))
# e_n * e_n-1 * ... * e_0 * a
# Could have used the multiplication operator, but writing
# the lambda was faster than looking it up.
print(np.vectorize(int)(reduce(lambda x, y: x * y, chain(reversed(e), [a]))))
Just run this after every step and I can be sure that my calculations are correct.
Also, what's not to love about that last line?