本文共 2692 字,大约阅读时间需要 8 分钟。
题目描述
如果A是个x行y列的矩阵,B是个y行z列的矩阵,把A和B相乘,其结果将是另一个x行z列的矩阵C。这个矩阵的每个元素是由下面的公式决定的矩阵的大小不超过100*100
输入描述:输入包含多组数据,每组数据包含:第一行包含一个正整数x,代表第一个矩阵的行数第二行包含一个正整数y,代表第一个矩阵的列数和第二个矩阵的行数第三行包含一个正整数z,代表第二个矩阵的列数之后x行,每行y个整数,代表第一个矩阵的值之后y行,每行z个整数,代表第二个矩阵的值
输出描述:
对于每组输入数据,输出x行,每行z个整数,代表两个矩阵相乘的结果
示例1
输入2321 2 33 2 11 22 13 3
输出
14 1310 11
代码实现:
import numpy as npdef 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
实现方法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()
转载地址:http://evlwk.baihongyu.com/