从csv文件读取矩阵内容,实现矩阵的转置,乘法。判断是否为矩阵等功能,非矩阵时的自定义异常。不使用numpy模块。
完整代码:
import csv
import pandas as pd
# 读取文件矩阵
def read_do1():
try:
csv_file = csv.reader(open('A.csv', 'r'))
content1 = []
print("A")
for line1 in csv_file:
print(line1)
content1.append(line1)
return content1
except:
print("文件A.csv不存在")
def read_do2():
try:
csv_file = csv.reader(open('B.csv', 'r'))
content2 = []
print("B")
for line2 in csv_file:
print(line2)
content2.append(line2)
return content2
except:
print("文件B.csv不存在")
# 矩阵转置
def turn(P):
F = []
M = []
for i in range(4):
for j in range(4):
M.append(P[j][i])
F = [M[i:i + 4] for i in range(0, len(M), 4)]
print("B转置后的矩阵为: ")
for line3 in F:
print(line3)
return F
# 自定义异常类
class MatrixMultiError(Exception):
def __init__(self, *args, **kwargs):
_args = ("A矩阵的行与B矩阵的列不相等!",) + args
super(MatrixMultiError, self).__init__(*_args, **kwargs)
# 自定义异常
class NotMatrixException(Exception):
def __init__(self, *args, **kwargs):
_args = ("不是矩阵",) + args
super(NotMatrixException, self).__init__(*_args, **kwargs)
# 抛出异常
def division(a, b):
if b != a :
raise MatrixMultiError("两个矩阵不能相乘!")
# 抛出异常
def if_juz(M):
n = len(M)
for i in range(n):
if len(M[i]) == n:
continue
else:
raise NotMatrixException("不是矩阵")
# 矩阵相乘
def ju(E,F):
print("A与B的转置C矩阵相乘得C矩阵:")
a = len(E)
b = len(F[0])
H3 = []
content3 = []
for i in range(a):
for j in range(a):
max = 0
for k in range(b):
max = max + int(E[i][k]) * int(F[j][k])
content3.append(max)
H3 = [content3[i:i + 4] for i in range(0, len(content3), 4)]
for line4 in H3:
print(line4)
return H3
# 判断是否为矩阵
def ifif(G):
a = len(G[0])
for i in range(a):
b = len(G[i])
if b != a:
return 0
return 1
def main():
A = read_do1()
B = read_do2()
C = []
n1 = ifif(A)
n2 = ifif(B)
if n1 != 1 and n2 != 1:
print("A,B都不是矩阵")
if_juz(A)
if_juz(B)
elif n1 == 1 and n2 != 1:
print("B不是矩阵")
if_juz(B)
elif n1 != 1 and n2 == 1:
print("A不是矩阵")
if_juz(A)
elif n1 == 1 and n2 == 1:
a = len(A[0])
b = len(B)
D = turn(B)
if a != b:
division(a, b)
else:
C = ju(A, D)
test = pd.DataFrame(data=C)
test.to_csv('C.csv', index=False)
main()