CCF刷题记录 -- 202305-2:矩阵运算 --python解法
2023.12.7
主要算法
- 矩阵置换
- 矩阵相乘
满分注意点
- 运算顺序,利用了矩阵运算法则中的(A*B)*c = A*(B*C)
# 矩阵置换
def zhihuan(a):
b=[]
for i in range(d):
c = []
for j in range(n):
c.append(a[j][i])
b.append(c)
return b
# 矩阵相乘
def ju_zheng_chen_fa(a,b):
c,c_1=[],[]
for i in range(len(a)):
for bj in range(len(b[0])):
sum=0
for j in range(len(b)):
sum += a[i][j]*b[j][bj]
c_1.append(sum)
c.append(c_1)
c_1=[]
return c
# w·矩阵
def dian_cheng(w,b):
c,c_1=[],[]
for i in range(len(w)):
for j in range(len(b[0])):
c_1.append(b[i][j] * w[i])
c.append(c_1)
c_1=[]
return c
n,d = list(map(int,input().split()))
list_q = [list(map(int,input().split())) for i in range(n)]
list_k = [list(map(int,input().split())) for i in range(n)]
list_v = [list(map(int,input().split())) for i in range(n)]
list_w = list(map(int,input().split()))
#计算顺序:k的转置*v -> k的转置*v*q -> k的转置*v*q*w
list_wqktv = dian_cheng(list_w,ju_zheng_chen_fa(list_q,ju_zheng_chen_fa(zhihuan(list_k),list_v)))
for i in list_wqktv:
print(' '.join(list(map(str,i))))