Advertisement
furas

Python - class Matrix - (Stackoverflow)

Jul 7th, 2020 (edited)
1,400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
  2. # date: 2020.07.07
  3. # https://stackoverflow.com/questions/62780283/why-am-i-getting-attributeerror-for-tuple-object
  4. # Why am i getting AttributeError for tuple object? [closed]
  5.  
  6. class Matrix:
  7.  
  8.     def __init__(self, rows=0, columns=0):
  9.         if rows == 0 and columns == 0:
  10.             self.rows, self.columns = map(int, input().split())
  11.         else:
  12.             self.rows = rows
  13.             self.columns = columns
  14.         self.dimension = (self.rows, self.columns)
  15.    
  16.     def pack_matrix(self):
  17.         self.value = tuple(tuple(int(i) for i in input().split()) for _ in range(self.rows))
  18.    
  19.     def __str__(self):
  20.         string = ""
  21.         for row in range(self.rows):
  22.             for col in range(self.columns):
  23.                 string = string + str(self.value[row][col]) +" "
  24.             string +="\n"
  25.         return string.strip()
  26.    
  27.     def __add__(self, other):
  28.         if self.rows == other.rows and self.columns == other.columns:
  29.             new_matrix = Matrix(self.rows, self.columns)
  30.            
  31.             all_rows = []
  32.             for row in range(self.rows):
  33.                 all_cols = []                
  34.                 for col in range(self.columns):
  35.                     all_cols.append(self.value[row][col] + other.value[row][col])
  36.                 all_cols = tuple(all_cols)
  37.                 all_rows.append(all_cols)
  38.             all_rows = tuple(all_rows)
  39.  
  40.             #new_matrix.value = tuple(tuple(int(i) for i in row) for row in range(all_rows))
  41.            
  42.             new_matrix.value = all_rows
  43.                
  44.             return new_matrix
  45.         else:
  46.             return "ERROR"
  47.        
  48. # --- main ---
  49.  
  50. m = Matrix(1, 2)
  51. m.value = ((1,2),)
  52.  
  53. n = Matrix(1, 2)
  54. n.value = ((3,4),)
  55.  
  56. print( (m + n).value )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement