Advertisement
Guest User

Untitled

a guest
Feb 16th, 2023
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.89 KB | Source Code | 0 0
  1. class Matrix:
  2. def __init__(self, name, m, n, values):
  3. self.name = name
  4. self.m = m
  5. self.n = n
  6. self.values = values
  7.  
  8. def __str__(self):
  9. rows = [self.values[i:i+self.n] for i in range(0, len(self.values), self.n)]
  10. return f'{self.name} = \n' + '\n'.join([' '.join(map(str, row)) for row in rows])
  11.  
  12. class MatrixMultiplier:
  13. def __init__(self):
  14. self.matrices = []
  15. #DEBUG#
  16. #self.matrices.append(Matrix('A', 3, 3, [1, -1, 0, 0, -2, 1, -2, 3, 1]))
  17. #self.matrices.append(Matrix('B', 3, 3, [1, 1, -1, 0, 2, 3, 1, 4, 1]))
  18. #######
  19. def create_paste(self, data):
  20. self.matrices.append(data)
  21.  
  22. def create_matrix(self, name):
  23. m = int(input(f'Introduceți numărul de rânduri pentru matricea {name}: '))
  24. n = int(input(f'Introduceți numărul de coloane pentru matricea {name}: '))
  25. values = []
  26. for i in range(m):
  27. for j in range(n):
  28. value = int(input(f'Introduceți valoarea pentru poziție ({i}, {j}) în matricea {name}: '))
  29. values.append(value)
  30. matrix = Matrix(name, m, n, values)
  31. self.matrices.append(matrix)
  32.  
  33. def add_matrices(self, name1, name2):
  34. matrix1 = next(matrix for matrix in self.matrices if matrix.name == name1)
  35. matrix2 = next(matrix for matrix in self.matrices if matrix.name == name2)
  36. if matrix1.m != matrix2.m or matrix1.n != matrix2.n:
  37. raise ValueError('Cele două matrice trebuie să aibă aceleași dimensiuni')
  38. result = [matrix1.values[i] + matrix2.values[i] for i in range(len(matrix1.values))]
  39. return Matrix(f'{name1}+{name2}', matrix1.m, matrix1.n, result)
  40.  
  41. def multiply_matrices(self, name1, name2):
  42. matrix1 = next(matrix for matrix in self.matrices if matrix.name == name1)
  43. matrix2 = next(matrix for matrix in self.matrices if matrix.name == name2)
  44. if matrix1.n != matrix2.m:
  45. raise ValueError('Numărul de coloane din prima matrice trebuie să se potrivească cu numărul de rânduri din a doua matrice')
  46. result = []
  47. for i in range(matrix1.m):
  48. for j in range(matrix2.n):
  49. val = 0
  50. for k in range(matrix1.n):
  51. val += matrix1.values[i * matrix1.n + k] * matrix2.values[k * matrix2.n + j]
  52. result.append(val)
  53. return Matrix(f'{name1}', matrix1.m, matrix2.n, result)
  54.  
  55. def scalar_multiply(self, name, scalar):
  56. matrix = next(matrix for matrix in self.matrices if matrix.name == name)
  57. result = [scalar * val for val in matrix.values]
  58. matrix.values = result
  59. matrix.name = f'{name}'
  60. return Matrix(matrix.name, matrix.m, matrix.n, result)
  61.  
  62. def flip_matrix(self, name):
  63. matrix = next(matrix for matrix in self.matrices if matrix.name == name)
  64. result = []
  65. for j in range(matrix.n):
  66. for i in range(matrix.m):
  67. result.append(matrix.values[i * matrix.n + j])
  68. matrix.values = result
  69. matrix.m, matrix.n = matrix.n, matrix.m
  70. matrix.name = f'{name}'
  71. return matrix
  72.  
  73. def subtract_matrices(self, name1, name2):
  74. matrix1 = next(matrix for matrix in self.matrices if matrix.name == name1)
  75. matrix2 = next(matrix for matrix in self.matrices if matrix.name == name2)
  76. if matrix1.m != matrix2.m or matrix1.n != matrix2.n:
  77. raise ValueError('Cele două matrice trebuie să aibă aceleași dimensiuni')
  78. result = [matrix1.values[i] - matrix2.values[i] for i in range(len(matrix1.values))]
  79. return Matrix(f'{name1}', matrix1.m, matrix1.n, result)
  80. def proprocess_transpose(self, ops):
  81. ops = ops.split()
  82. for i in range(len(ops)):
  83. if ops[i] == 't':
  84. name = ops[i - 1]
  85. matrix = self.flip_matrix(name)
  86. self.matrices[self.matrices.index(next(matrix for matrix in self.matrices if matrix.name == matrix.name))] = matrix
  87. ops.remove(ops[i])
  88. ops[i-1] = f'{name}'
  89. return ' '.join(ops)
  90.  
  91. def parse_parentheses(self,input_str):
  92. stack = []
  93. term = ""
  94. if "(" in input_str:
  95. for char in input_str:
  96. if char in ['+', '-', '*']:
  97. if term:
  98. stack.append(term)
  99. term = ""
  100. stack.append(char)
  101. elif char == "(":
  102. if term:
  103. stack.append(term)
  104. term = ""
  105. stack.append(char)
  106. elif char == ")":
  107. if term:
  108. stack.append(term)
  109. term = ""
  110. temp = []
  111. while stack and stack[-1] != "(":
  112. temp.append(stack.pop())
  113. if stack[-1] == "(":
  114. stack.pop()
  115. if temp:
  116. stack += temp[::-1]
  117. else:
  118. term += char
  119.  
  120. if term:
  121. stack.append(term)
  122. for op in ['*', '-', '+']:
  123. while op in stack:
  124. op_index = stack.index(op)
  125. stack.pop(op_index)
  126. stack.append(op)
  127. if op not in stack[op_index + 1:]:
  128. break
  129.  
  130. return stack
  131. else:
  132. return [input_str]
  133.  
  134. def custom_input(self, equation):
  135. equation = self.parse_parentheses(equation)
  136. equation_list = []
  137. temp_str = ""
  138. if len(equation)>1:
  139. #IT IS FIXED SO WORKS FOR 2 () sets
  140. _n1 = equation[0][0]
  141. _n2 = equation[1][0]
  142. ###################################
  143. for ec in equation:
  144. if ec not in ['+', '-', '*'] and len(ec) > 1:
  145. equation_list.append(ec)
  146. elif ec in ['+', '-', '*']:
  147. equation_list.append(f'{_n1}{ec}{_n2}')
  148. else:
  149. equation_list.append(equation[0])
  150. for equation in equation_list:
  151. if '*' in equation:
  152. matrices = equation.split('*')
  153. matrix1 = next(matrix for matrix in self.matrices if matrix.name == matrices[0])
  154. matrix2 = next(matrix for matrix in self.matrices if matrix.name == matrices[1])
  155. result_matrix = self.multiply_matrices(matrix1.name, matrix2.name)
  156. matrix_name = matrix1.name
  157. elif '-' in equation:
  158. matrices = equation.split('-')
  159. matrix1 = next(matrix for matrix in self.matrices if matrix.name == matrices[0])
  160. matrix2 = next(matrix for matrix in self.matrices if matrix.name == matrices[1])
  161. result_matrix = self.subtract_matrices(matrix1.name, matrix2.name)
  162. matrix_name = matrix1.name
  163. elif 'o' in equation: # SELF MULTIPLY
  164. matrices = equation.split('o')
  165. matrix = next(matrix for matrix in self.matrices if matrix.name == matrices[0])
  166. result_matrix = self.multiply_matrices(matrix.name, matrix.name)
  167. matrix_name = matrix.name
  168. elif 's' in equation:
  169. matrices = equation.split('s')
  170. matrix = next(matrix for matrix in self.matrices if matrix.name == matrices[0])
  171. scalar = float(matrices[1])
  172. result_matrix = self.scalar_multiply(matrix.name, scalar)
  173. matrix_name = matrix.name
  174. elif 't' in equation:
  175. matrix_name = equation.split('t')[0]
  176. matrix = next(matrix for matrix in self.matrices if matrix.name == matrix_name)
  177. result_matrix = self.flip_matrix(matrix.name)
  178. matrix_name = matrix.name
  179. else:
  180. raise ValueError(f"Invalid equation '{equation}'")
  181. if result_matrix is not None:
  182. self.matrices[self.matrices.index(next(matrix for matrix in self.matrices if matrix.name == matrix_name))] = result_matrix
  183.  
  184. return result_matrix
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194. def print_menu():
  195. print('1. Creați matrice')
  196. print('2. Înmulțiți matrice')
  197. print('3. Înmulțire scalară')
  198. print('4. Adăugați matrice')
  199. print('5. Scăderea matricilor')
  200. print('6. Flip Matrix')
  201. print('7. Intrare personalizată')
  202. #print('8. Creați matrice din input paste')
  203. print('8. Ieșire')
  204. def main():
  205. matrix_multiplier = MatrixMultiplier()
  206. while True:
  207. print_menu()
  208. choice = input('Introdu alegerea ta: ')
  209. if choice == '1':
  210. name = input('Introduceți numele matricei: ')
  211. matrix_multiplier.create_matrix(name)
  212. elif choice == '2':
  213. name1 = input('Introduceți numele primei matrice: ')
  214. name2 = input('Introduceți numele celei de-a doua matrice: ')
  215. try:
  216. result = matrix_multiplier.multiply_matrices(name1, name2)
  217. print(result)
  218. except ValueError as e:
  219. print(e)
  220. elif choice == '3':
  221. name = input('Introduceți numele primei matrice: ')
  222. scalar = int(input('Introduceți scalarul: '))
  223. result = matrix_multiplier.scalar_multiply(name, scalar)
  224. print(result)
  225. elif choice == '4':
  226. name1 = input('Introduceți numele primei matrice: ')
  227. name2 = input('Introduceți numele celei de-a doua matrice: ')
  228. try:
  229. result = matrix_multiplier.add_matrices(name1, name2)
  230. print(result)
  231. except ValueError as e:
  232. print(e)
  233. elif choice == '5':
  234. name1 = input('Introduceți numele primei matrice: ')
  235. name2 = input('Introduceți numele celei de-a doua matrice: ')
  236. try:
  237. result = matrix_multiplier.subtract_matrices(name1, name2)
  238. print(result)
  239. except ValueError as e:
  240. print(e)
  241. elif choice == '6':
  242. name = input('Introduceți numele matrice: ')
  243. result = matrix_multiplier.flip_matrix(name)
  244. print(result)
  245. elif choice == '7':
  246. update_con = input('Vrei sa salvezi noile valori?: ')
  247. if update_con in ['yes', 'da', 'y']:
  248. update_con = 1
  249. operations = input('Introduceți succesiunea operațiilor cu matrice: ')
  250. try:
  251. result = matrix_multiplier.custom_input(operations)
  252. print(result)
  253. except (ValueError, IndexError) as e:
  254. print(e)
  255. else:
  256. print('Alegere nevalidă')
  257.  
  258. if __name__ == '__main__':
  259. main()
  260.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement