1.串列作為資料結構
def MatrixProduct(a, b):
temp2 = []
for i in range(len(a)):
temp1 = []
for j in range(len(b[0])):
total = 0
for k in range(len(a[0])):
total += a[i][k] * b[k][j]
temp1.append(total)
temp2.append(temp1)
return temp2
print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))時間復雜度太高O(n^3)
以后再想辦法用矩陣快速冪來優化,降低時間復雜度
2.numpy中ndarray作為資料結構
(注意numpy陣列的a*b指的并不是矩陣乘法,a.dot(b)或者numpy.dot(a,b))
import numpy as np
def MatrixProduct(a, b):
a=np.array(a)
b=np.array(b)
c=np.dot(a,b)
return c.tolist()
print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))3.numpy中mat作為資料結構
這種矩陣格式就可以a*b了
import numpy as np
def MatrixProduct(a, b):
a=np.mat(a)
b=np.mat(b)
c=a*b
return c.tolist()
print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/124168.html
標籤:Python
上一篇:03.DRF-設計方法
下一篇:第1章-起 步
