Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.96 KB | None | 0 0
  1. #Mnożenie macierzy
  2. import re
  3. import os.path
  4. class File():
  5.     def __init__(self, name_of_file=None):
  6.         assert isinstance(name_of_file,str)
  7.         self.path=name_of_file
  8.         self.matrixes = None
  9.         self.text = self.read_file_from_desktop(name_of_file)
  10.         self.parsing_input()
  11.  
  12.     def read_file_from_desktop(self,name_of_file): # wczytywanie pliku tekstowego z pulpitu.
  13.         path = os.path.expanduser('~/Desktop/'+name_of_file)
  14.         file = open(path, 'r')                     # otwarcie
  15.         file_content = file.read()                 # czytanie
  16.         file.close()                               # zamkniecie
  17.         return file_content
  18.  
  19.     def save_file_on_desktop(self,name_of_file,string):
  20.         if self.path==name_of_file:
  21.             self.error("Warning, trying to overwrite input file")
  22.         path = os.path.expanduser('~/Desktop/'+name_of_file)
  23.         file = open(path, 'w')
  24.         file_content = file.write(string)
  25.         file.close()
  26.         return file_content
  27.  
  28.     def parsing_input(self):
  29.         self.text=re.sub('[\s+]', '', self.text)   # usuniecie bialych znakow ze stringa
  30.         kwadratowe_nawiasy = self.text.split("*")  # przypisanie tego co jest pomiedzy mnożeniem jako listy
  31.         for matrix in kwadratowe_nawiasy:          # dla każdego elementu tej listy
  32.             if re.match("^\[[\S]*\]$",matrix):     # sprawdź prosty regex czy sa nawiasy, a w środku cokolwiek
  33.                 pass
  34.             else:
  35.                 self.error()
  36.             for row in matrix.replace("[", '').replace("]", '').split(";"):
  37.                 for elem in (row.split(",")):
  38.                     try:
  39.                         float(elem)                  # sprawdzenie czy element jest liczba
  40.                     except:
  41.                         self.error("elements of matrix must be intigers or floats")
  42.  
  43.         if self.check_dimensions(kwadratowe_nawiasy):
  44.             if self.check_multiply_dimensions(kwadratowe_nawiasy):
  45.                 self.matrixes = kwadratowe_nawiasy
  46.             else:
  47.                 self.error("Error using * number of columns in one matrix must be equal to number of rows in another")
  48.         else:
  49.             self.error("Error using * Inner matrix dimensions must agree.")
  50.  
  51.     def error(self,param='Error parsing input'):
  52.         raise Exception(param) #Expression or statement is incomplete or incorrect.
  53.  
  54.     def check_dimensions(self,matrixes):#check if matrix have equal number of element in each column
  55.         conditions=[]
  56.         for matrix in matrixes:
  57.             count_of_commas = []
  58.             for elem in (matrix.split(';')):
  59.                 count_of_commas.append(elem.count(","))
  60.             conditions.append(count_of_commas.count(count_of_commas[0]) == len(count_of_commas))
  61.         return(all(conditions))
  62.  
  63.     def check_multiply_dimensions(self,matrixes):#pierwsza musi mieć tyle kolumn, co druga wierszy.
  64.         if len(matrixes)<2:
  65.             self.error("Need second matrix to multiply")
  66.         elif self.number_of_columns(matrixes[0]) == self.number_of_rows(matrixes[1]):
  67.             size_of_product = [self.number_of_rows(matrixes[0]),self.number_of_columns(matrixes[1])]
  68.         else:
  69.             return False
  70.         if len(matrixes)==2:
  71.             return True
  72.         else:
  73.             for matrix in matrixes[2:]:
  74.                 if size_of_product[1]==self.number_of_rows(matrix):
  75.                     size_of_product=[size_of_product[0],self.number_of_columns(matrix)]
  76.                     pass
  77.                 else:
  78.                     return False
  79.             return True
  80.  
  81.     def number_of_rows(self,matrix):
  82.         return matrix.count(";")+1
  83.  
  84.     def number_of_columns(self,matrix):
  85.         return matrix.split(";")[0].count(",")+1
  86.  
  87.  
  88. class Matrix():
  89.     def __init__(self,matrixes):
  90.         self.matrixes=self.list_of_lists(matrixes)
  91.         self.end_product=self.lets_do_multiply(self.matrixes)
  92.  
  93.     def multiply_of_two(self,a,b):
  94.         zip_b = zip(*b)
  95.         zip_b = list(zip_b)
  96.         return [[sum(ele_a * ele_b for ele_a, ele_b in zip(row_a, col_b))
  97.                  for col_b in zip_b] for row_a in a]
  98.  
  99.     def lets_do_multiply(self,matrixes):
  100.         product=self.multiply_of_two(matrixes[0],matrixes[1])
  101.         if len(matrixes)>2:
  102.             for matrix in matrixes[2:]:
  103.                 product=self.multiply_of_two(product,matrix)
  104.         return re.sub("\], \[", '; ', str(product)[1:-1])
  105.  
  106.     def list_of_lists(self,matrixes):
  107.         lista=[]
  108.         for matrix in matrixes:
  109.             macierz=[]
  110.             for row in matrix.replace("[", '').replace("]", '').split(";"):
  111.                 rzad=[]
  112.                 for elem in (row.split(",")):
  113.                     rzad.append(float(elem))
  114.                 macierz.append(rzad)
  115.             lista.append(macierz)
  116.         return lista
  117.  
  118. File=File("matrixes.txt")
  119. product = Matrix(File.matrixes)
  120. File.save_file_on_desktop("wynik.txt","wynik = {0}".format(str(product.end_product)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement