python有很多功能庫,這些庫對于編程很有幫助,可以在pycharm的Project Interpreter導入庫,例如numpy、os、scipy等比較基礎(chǔ)的庫,
import numpy as np
from scipy import linalg
import os
#輸入矩陣維數(shù)
print("你好,這里是計算稀疏矩陣線性方程組的地方,非誠勿擾!")
dism_num = input("你的A矩陣維數(shù)是:")
dism_num = int(dism_num)
print("接下來請你依次輸入矩陣的行向量(注意只能輸入英文逗號,):")
A =[]
#X =[]
for i in range(1,dism_num+1):
a=input("第"+str(i)+"行向量是:")
alist = a.split(",")
alist = [int(alist[j]) for j in range(len(alist))]
A.append(alist)
print("你所輸入的矩陣行向量是:")
print(A)
#記錄輸入的X矩陣
#輸入向量b
print("輸入b向量")
b = input("b向量是:")
b_list = b.split(",")
b_list = [int(b_list[j]) for j in range(len(b_list))]
print("你輸入的b向量是:")
print(b_list)
#記錄b向量
#詢問是否計算單個答案(單元素)
ask = input("是否只需求解單個值:(是或否)")
while(True):
if ask == '是':
ask_a = 'T'
ask_num = input("請繼續(xù)輸入你所需要的答案序號:")
ask_num = int(ask_num)
if ask_num=dism_num and ask_num>0:
print("OK,馬上幫你計算")
break
else:
print("輸入的值超出矩陣維數(shù),請重新輸入:")
if ask == '否':
ask_a = 'F'
break
#詢問完成,只有當用戶輸入正確的序號才可以進行計算,否則重新詢問
#開始計算x向量了
A = np.array(A)
b = np.array(b_list)
x = linalg.solve(A,b)
print("計算的結(jié)果的:")
if ask_a == 'F':
print(x)
if ask_a =='T':
print(x[ask_num-1])
#計算完x向量了
os.system("pause")
#用于py文件結(jié)束玩暫停顯示結(jié)果
import threading, time
import numpy as np
res = []
class MyThread(threading.Thread):
def __init__(self,i,j,m1,m2):
threading.Thread.__init__(self)
self.x, self.y = i,j
self.m1, self.m2 = m1, m2
def run(self):
global res, lock
if lock.acquire():
m1 = self.m1[self.m1[:,0]==self.x]
m2 = self.m2[self.m2[:,1]==self.y]
value = 0.
for item1 in m1:
for item2 in m2:
if item1[1] == item2[0]:
value += item1[2]*item2[2]
res.append([self.x,self.y,value])
lock.release()
if "__main__" == __name__:
m1 = [[2,2],[0,0,1],[0,1,2],[1,0,3],[1,1,4]]
m2 = [[2,3],[0,0,2],[0,2,1],[1,2,3],[1,1,4]]
s1, s2 = m1[0], m2[0]
assert s1[1]==s2[0], 'mismatch'
m1_value = np.array(m1[1:])
m2_value = np.array(m2[1:])
rows, cols = s1[0], s2[1]
res.append([rows, cols])
ThreadList = []
lock = threading.Lock()
for i in range(rows):
for j in range(cols):
t = MyThread(i,j,m1_value,m2_value)
ThreadList.append(t)
for t in ThreadList:
t.start()
for t in ThreadList:
t.join()
print (res)