题目描述
如果A是个x行y列的矩阵,B是个y行z列的矩阵,把A和B相乘,其结果将是另一个x行z列的矩阵C。这个矩阵的每个元素是由下面的公式决定的
矩阵的大小不超过100*100
输入描述:
输入包含多组数据,每组数据包含:
第一行包含一个正整数x,代表第一个矩阵的行数
第二行包含一个正整数y,代表第一个矩阵的列数和第二个矩阵的行数
第三行包含一个正整数z,代表第二个矩阵的列数
之后x行,每行y个整数,代表第一个矩阵的值
之后y行,每行z个整数,代表第二个矩阵的值
输出描述:
对于每组输入数据,输出x行,每行z个整数,代表两个矩阵相乘的结果
示例1
输入
2
3
2
1 2 3
3 2 1
1 2
2 1
3 3
输出
14 13
10 11
代码实现:
import numpy as np
def func():
while True:
try:
#列
n1_col = int(input())
#行
n1_row = int(input())
n2_col = n1_row
n2_row = int(input())
#print(n1_col,n1_row,n2_col,n2_row)
list1 = []
for i in range(n1_col):
list1.append(list(map(int,input().split())))
#print(list1)
list2 = []
for i in range(n2_col):
list2.append(list(map(int,input().split())))
#print(list2)
np1 = np.array(list1)
np2 = np.array(list2)
val = np.dot(np1,np2)
#print(val)
for i in val:
print(" ".join(list(map(str,list(i)))))
except Exception as e:
#print(e)
break
if __name__ == '__main__':
func()
实现方法2:
def func():
while True:
try:
#列
n1_col = int(input())
#行
n1_row = int(input())
n2_col = n1_row
n2_row = int(input())
list1 = []
for i in range(n1_col):
list1.append(list(map(int,input().split())))
list2 = []
for i in range(n2_col):
list2.append(list(map(int,input().split())))
#行列转换
lists = list(map(list,zip(*list2)))
for n1,v1 in enumerate(list1):
sum1 = 0
n3 = 0
list_val = []
while n3<len(lists):
vals = 0
for n2,v2 in enumerate(v1):
val = lists[n3][n2] * v2
vals +=val
n3 +=1
list_val.append(vals)
print(" ".join(list(map(str,list_val))))
except Exception as e:
#print(e)
break
if __name__ == '__main__':
func()
实现方法3:
def func():
while True:
try:
#列
n1_col = int(input())
#行
n1_row = int(input())
n2_col = n1_row
n2_row = int(input())
list1 = []
for i in range(n1_col):
list1.append(list(map(int,input().split())))
list2 = []
for i in range(n2_col):
list2.append(list(map(int,input().split())))
#行列转换
lists = list(map(list,zip(*list2)))
for x in range(n1_col):
results = []
for y in range(n2_row):
val = [n1*n2 for n1,n2 in zip(list1[x],lists[y])]
results.append(sum(val))
print(" ".join(list(map(str,results))))
except Exception as e:
#print(e)
break
if __name__ == '__main__':
func()