Advertisement
1211466520

p3--matrix

Apr 24th, 2025
166
0
29 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.69 KB | None | 0 0
  1. # Copyright (c) 2025, HAN
  2. # Environment: Python 3.12.8, Win 10
  3.  
  4.  
  5. class Matrix:
  6.     def __init__(
  7.         self, rows: int = None, cols: int = None, data: list[list[float]] = None
  8.     ):
  9.         """
  10.        Init a matrix with given rows and cols, or with given data
  11.  
  12.        Args:
  13.            rows (int, optional): Row count of matrix. Defaults to None.
  14.            cols (int, optional): Col count of matrix. Defaults to None.
  15.            data (list[list[float]], optional): Data of matrix. Defaults to None.
  16.  
  17.        Raises:
  18.            ValueError: Invalid parameters
  19.        """
  20.         if data is not None:
  21.             if not Matrix.is_valid(data):
  22.                 raise ValueError("Invalid matrix shape")
  23.             self.data = data
  24.             self.rows = len(data)
  25.             self.cols = len(data[0])
  26.         elif rows is not None and cols is not None:
  27.             self.rows = rows
  28.             self.cols = cols
  29.             self.data = [[0] * cols for _ in range(rows)]
  30.         # What if rows, cols and data are given at the same time?
  31.         else:
  32.             raise ValueError("Invalid parameters")
  33.  
  34.     def __str__(self):
  35.         str = ""
  36.         for row in self.data:
  37.             for col in row:
  38.                 str += f"{col:3d}"
  39.             str += "\n"
  40.         return str
  41.  
  42.     # operation 1
  43.     def is_valid(matrix: list[list[float]]) -> bool:
  44.         """
  45.        Is the matrix valid?
  46.  
  47.        Args:
  48.            matrix (list[list[float]]): the matrix to check
  49.  
  50.        Returns:
  51.            bool: a bool indicates if the matrix is valid
  52.        """
  53.         # check valid object and type
  54.         if not matrix or not isinstance(matrix, list):
  55.             return False
  56.         if not matrix[0] or not isinstance(matrix[0], list):
  57.             return False
  58.  
  59.         # every row should has same count of cols
  60.         cols_count_of_first_row = len(matrix[0])
  61.         for row in matrix:
  62.             if not row or not isinstance(row, list):
  63.                 return False
  64.             if len(row) != cols_count_of_first_row:
  65.                 return False
  66.  
  67.         return True
  68.  
  69.     # operation 2
  70.     def transpose(self):
  71.         t = Matrix(self.cols, self.rows)
  72.         for i in range(self.rows):
  73.             for j in range(self.cols):
  74.                 t.data[j][i] = self.data[i][j]
  75.         return t
  76.  
  77.     # operation 3.1
  78.     def sum_of_each_row(self):
  79.         return [sum(row) for row in self.data]
  80.  
  81.     # operation 3.2
  82.     def product_of_each_column(self):
  83.         return [self.product_of_column(i) for i in range(self.cols)]
  84.  
  85.     def product_of_column(self, col):
  86.         product = 1
  87.         for i in range(self.rows):
  88.             product *= self.data[i][col]
  89.         return product
  90.  
  91.     # operation 4
  92.     def clockwise_spiral_traverse(self):
  93.         answer = []
  94.         # visited[i][j] = True if self.data[i][j] is traversed (and added to answer)
  95.         visited = [[False] * self.cols for _ in range(self.rows)]
  96.  
  97.         # start at (0, 0)
  98.         answer.append(self.data[0][0])
  99.         visited[0][0] = True
  100.         i, j = 0, 0
  101.         size = self.rows * self.cols
  102.         while len(answer) < size:
  103.             # go right till the end
  104.             while j + 1 < self.cols and not visited[i][j + 1]:
  105.                 j += 1
  106.                 answer.append(self.data[i][j])
  107.                 visited[i][j] = True
  108.             # go down till the end
  109.             while i + 1 < self.rows and not visited[i + 1][j]:
  110.                 i += 1
  111.                 answer.append(self.data[i][j])
  112.                 visited[i][j] = True
  113.             # go left till the end
  114.             while j - 1 >= 0 and not visited[i][j - 1]:
  115.                 j -= 1
  116.                 answer.append(self.data[i][j])
  117.                 visited[i][j] = True
  118.             # go up till the end
  119.             while i - 1 >= 0 and not visited[i - 1][j]:
  120.                 i -= 1
  121.                 answer.append(self.data[i][j])
  122.                 visited[i][j] = True
  123.  
  124.         return answer
  125.  
  126.     # operation 5
  127.     def rotate_90_clockwise_and_180(self):
  128.         rotate_90_clockwise = self.rotate()
  129.         rotate_180 = rotate_90_clockwise.rotate()
  130.         return rotate_90_clockwise, rotate_180
  131.  
  132.     def rotate(self):
  133.         r = Matrix(self.cols, self.rows)
  134.         for i in range(self.rows):
  135.             for j in range(self.cols):
  136.                 r.data[j][self.rows - 1 - i] = self.data[i][j]
  137.         return r
  138.  
  139.  
  140. def test_and_print(m: list[list[float]]):
  141.     """
  142.    Check my answer to problems
  143.    """
  144.     print("*" * 40)
  145.     print("Inputed nested list:\n", m, sep="")
  146.     try:
  147.         m = Matrix(data=m)
  148.     except ValueError as e:
  149.         print(e)
  150.         return
  151.  
  152.     print("Problem 2 Transpose:\n", m.transpose(), sep="")
  153.     print("Problem 3.1 sum of each row:\n", m.sum_of_each_row(), sep="")
  154.     print(
  155.         "Problem 3.2 product of each column:\n",
  156.         m.product_of_each_column(),
  157.         sep="",
  158.     )
  159.     print(
  160.         "Problem 4 clockwise spiral traverse:\n",
  161.         m.clockwise_spiral_traverse(),
  162.         sep="",
  163.     )
  164.     m_rotate_90, m_rotate_180 = m.rotate_90_clockwise_and_180()
  165.     print("Problem 4 rotate 90 clockwise:\n", m_rotate_90, sep="")
  166.     print("Problem 4 rotate 180:\n", m_rotate_180, sep="")
  167.  
  168.  
  169. if __name__ == "__main__":
  170.     test_and_print(None)
  171.     test_and_print([])
  172.     test_and_print("123")
  173.     test_and_print([[]])
  174.     test_and_print([[0]])
  175.     test_and_print([[1, 2], [3]])
  176.  
  177.     # row=3, col=4
  178.     m1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
  179.     test_and_print(m1)
  180.  
  181.     # row=4, col=3
  182.     m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
  183.     test_and_print(m2)
  184.  
  185.     # row=3, col=3
  186.     m3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  187.     test_and_print(m3)
  188.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement