Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Mnożenie macierzy
- import re
- import os.path
- class File():
- def __init__(self, name_of_file=None):
- assert isinstance(name_of_file,str)
- self.path=name_of_file
- self.matrixes = None
- self.text = self.read_file_from_desktop(name_of_file)
- self.parsing_input()
- def read_file_from_desktop(self,name_of_file): # wczytywanie pliku tekstowego z pulpitu.
- path = os.path.expanduser('~/Desktop/'+name_of_file)
- file = open(path, 'r') # otwarcie
- file_content = file.read() # czytanie
- file.close() # zamkniecie
- return file_content
- def save_file_on_desktop(self,name_of_file,string):
- if self.path==name_of_file:
- self.error("Warning, trying to overwrite input file")
- path = os.path.expanduser('~/Desktop/'+name_of_file)
- file = open(path, 'w')
- file_content = file.write(string)
- file.close()
- return file_content
- def parsing_input(self):
- self.text=re.sub('[\s+]', '', self.text) # usuniecie bialych znakow ze stringa
- kwadratowe_nawiasy = self.text.split("*") # przypisanie tego co jest pomiedzy mnożeniem jako listy
- for matrix in kwadratowe_nawiasy: # dla każdego elementu tej listy
- if re.match("^\[[\S]*\]$",matrix): # sprawdź prosty regex czy sa nawiasy, a w środku cokolwiek
- pass
- else:
- self.error()
- for row in matrix.replace("[", '').replace("]", '').split(";"):
- for elem in (row.split(",")):
- try:
- float(elem) # sprawdzenie czy element jest liczba
- except:
- self.error("elements of matrix must be intigers or floats")
- if self.check_dimensions(kwadratowe_nawiasy):
- if self.check_multiply_dimensions(kwadratowe_nawiasy):
- self.matrixes = kwadratowe_nawiasy
- else:
- self.error("Error using * number of columns in one matrix must be equal to number of rows in another")
- else:
- self.error("Error using * Inner matrix dimensions must agree.")
- def error(self,param='Error parsing input'):
- raise Exception(param) #Expression or statement is incomplete or incorrect.
- def check_dimensions(self,matrixes):#check if matrix have equal number of element in each column
- conditions=[]
- for matrix in matrixes:
- count_of_commas = []
- for elem in (matrix.split(';')):
- count_of_commas.append(elem.count(","))
- conditions.append(count_of_commas.count(count_of_commas[0]) == len(count_of_commas))
- return(all(conditions))
- def check_multiply_dimensions(self,matrixes):#pierwsza musi mieć tyle kolumn, co druga wierszy.
- if len(matrixes)<2:
- self.error("Need second matrix to multiply")
- elif self.number_of_columns(matrixes[0]) == self.number_of_rows(matrixes[1]):
- size_of_product = [self.number_of_rows(matrixes[0]),self.number_of_columns(matrixes[1])]
- else:
- return False
- if len(matrixes)==2:
- return True
- else:
- for matrix in matrixes[2:]:
- if size_of_product[1]==self.number_of_rows(matrix):
- size_of_product=[size_of_product[0],self.number_of_columns(matrix)]
- pass
- else:
- return False
- return True
- def number_of_rows(self,matrix):
- return matrix.count(";")+1
- def number_of_columns(self,matrix):
- return matrix.split(";")[0].count(",")+1
- class Matrix():
- def __init__(self,matrixes):
- self.matrixes=self.list_of_lists(matrixes)
- self.end_product=self.lets_do_multiply(self.matrixes)
- def multiply_of_two(self,a,b):
- zip_b = zip(*b)
- zip_b = list(zip_b)
- return [[sum(ele_a * ele_b for ele_a, ele_b in zip(row_a, col_b))
- for col_b in zip_b] for row_a in a]
- def lets_do_multiply(self,matrixes):
- product=self.multiply_of_two(matrixes[0],matrixes[1])
- if len(matrixes)>2:
- for matrix in matrixes[2:]:
- product=self.multiply_of_two(product,matrix)
- return re.sub("\], \[", '; ', str(product)[1:-1])
- def list_of_lists(self,matrixes):
- lista=[]
- for matrix in matrixes:
- macierz=[]
- for row in matrix.replace("[", '').replace("]", '').split(";"):
- rzad=[]
- for elem in (row.split(",")):
- rzad.append(float(elem))
- macierz.append(rzad)
- lista.append(macierz)
- return lista
- File=File("matrixes.txt")
- product = Matrix(File.matrixes)
- File.save_file_on_desktop("wynik.txt","wynik = {0}".format(str(product.end_product)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement