写Homework之前需要写Matrix的一些函数,也就是完成Matrix Class Homework。这篇文章也就先写到这里先。
这个类主要实现矩阵的加法,转置,矩阵和向量的乘法,矩阵和矩阵的乘法。
from vec import *
def getitem(M, k):
"Returns the value of entry k in M. The value of k should be a pair."
assert k[0] in M.D[0] and k[1] in M.D[1]
if k in M.f:return M.f[k]
else:return 0
def setitem(M, k, val):
"Sets the element of v with label k to be val. The value of k should be a pair"
assert k[0] in M.D[0] and k[1] in M.D[1]
M.f.update({(k[0],k[1]):val})
def add(A, B):
"Returns the sum of A and B"
assert A.D == B.D
return Mat((A.D[0],A.D[1]),{(x,y):getitem(A,(x,y))+getitem(B,(x,y)) for x in A.D[0] for y in A.D[1]})
def scalar_mul(M, alpha):
"Returns the product of scalar alpha with M"
return Mat((M.D[0],M.D[1]),{(x,y):getitem(M,(x,y))*alpha for x in M.D[0] for y in M.D[1]})
def equal(A, B):
"Returns true iff A is equal to B"
assert A.D == B.D
return {getitem(A,(x,y))==getitem(B,(x,y)) for x in A.D[0] for y in A.D[1]}=={True}
def transpose(M):
"Returns the transpose of M"
return Mat((M.D[1],M.D[0]),{(y,x):getitem(M,(x,y)) for x in M.D[0] for y in M.D[1]})
def vector_matrix_mul(v, M):
"Returns the product of vector v and matrix M"
assert M.D[0] == v.D
return Vec(M.D[1],{y:sum([v[x]*getitem(M,(x,y)) for x in M.D[0]]) for y in M.D[1]})
def matrix_vector_mul(M, v):
"Returns the product of matrix M and vector v"
assert M.D[1] == v.D
return Vec(M.D[0],{x:sum([getitem(M,(x,y))*v[y] for y in M.D[1]]) for x in M.D[0]})
def matrix_matrix_mul(A, B):
"Returns the product of A and B"
assert A.D[1] == B.D[0]
return Mat((A.D[0],B.D[1]),{(x,y):sum([getitem(A,(x,k))*getitem(B,(k,y)) for k in A.D[1]]) for x in A.D[0] for y in B.D[1]})