Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Copyright (c) 2025, HAN
- # Environment: Python 3.12.8, Win 10
- class Matrix:
- def __init__(
- self, rows: int = None, cols: int = None, data: list[list[float]] = None
- ):
- """
- Init a matrix with given rows and cols, or with given data
- Args:
- rows (int, optional): Row count of matrix. Defaults to None.
- cols (int, optional): Col count of matrix. Defaults to None.
- data (list[list[float]], optional): Data of matrix. Defaults to None.
- Raises:
- ValueError: Invalid parameters
- """
- if data is not None:
- if not Matrix.is_valid(data):
- raise ValueError("Invalid matrix shape")
- self.data = data
- self.rows = len(data)
- self.cols = len(data[0])
- elif rows is not None and cols is not None:
- self.rows = rows
- self.cols = cols
- self.data = [[0] * cols for _ in range(rows)]
- # What if rows, cols and data are given at the same time?
- else:
- raise ValueError("Invalid parameters")
- def __str__(self):
- str = ""
- for row in self.data:
- for col in row:
- str += f"{col:3d}"
- str += "\n"
- return str
- # operation 1
- def is_valid(matrix: list[list[float]]) -> bool:
- """
- Is the matrix valid?
- Args:
- matrix (list[list[float]]): the matrix to check
- Returns:
- bool: a bool indicates if the matrix is valid
- """
- # check valid object and type
- if not matrix or not isinstance(matrix, list):
- return False
- if not matrix[0] or not isinstance(matrix[0], list):
- return False
- # every row should has same count of cols
- cols_count_of_first_row = len(matrix[0])
- for row in matrix:
- if not row or not isinstance(row, list):
- return False
- if len(row) != cols_count_of_first_row:
- return False
- return True
- # operation 2
- def transpose(self):
- t = Matrix(self.cols, self.rows)
- for i in range(self.rows):
- for j in range(self.cols):
- t.data[j][i] = self.data[i][j]
- return t
- # operation 3.1
- def sum_of_each_row(self):
- return [sum(row) for row in self.data]
- # operation 3.2
- def product_of_each_column(self):
- return [self.product_of_column(i) for i in range(self.cols)]
- def product_of_column(self, col):
- product = 1
- for i in range(self.rows):
- product *= self.data[i][col]
- return product
- # operation 4
- def clockwise_spiral_traverse(self):
- answer = []
- # visited[i][j] = True if self.data[i][j] is traversed (and added to answer)
- visited = [[False] * self.cols for _ in range(self.rows)]
- # start at (0, 0)
- answer.append(self.data[0][0])
- visited[0][0] = True
- i, j = 0, 0
- size = self.rows * self.cols
- while len(answer) < size:
- # go right till the end
- while j + 1 < self.cols and not visited[i][j + 1]:
- j += 1
- answer.append(self.data[i][j])
- visited[i][j] = True
- # go down till the end
- while i + 1 < self.rows and not visited[i + 1][j]:
- i += 1
- answer.append(self.data[i][j])
- visited[i][j] = True
- # go left till the end
- while j - 1 >= 0 and not visited[i][j - 1]:
- j -= 1
- answer.append(self.data[i][j])
- visited[i][j] = True
- # go up till the end
- while i - 1 >= 0 and not visited[i - 1][j]:
- i -= 1
- answer.append(self.data[i][j])
- visited[i][j] = True
- return answer
- # operation 5
- def rotate_90_clockwise_and_180(self):
- rotate_90_clockwise = self.rotate()
- rotate_180 = rotate_90_clockwise.rotate()
- return rotate_90_clockwise, rotate_180
- def rotate(self):
- r = Matrix(self.cols, self.rows)
- for i in range(self.rows):
- for j in range(self.cols):
- r.data[j][self.rows - 1 - i] = self.data[i][j]
- return r
- def test_and_print(m: list[list[float]]):
- """
- Check my answer to problems
- """
- print("*" * 40)
- print("Inputed nested list:\n", m, sep="")
- try:
- m = Matrix(data=m)
- except ValueError as e:
- print(e)
- return
- print("Problem 2 Transpose:\n", m.transpose(), sep="")
- print("Problem 3.1 sum of each row:\n", m.sum_of_each_row(), sep="")
- print(
- "Problem 3.2 product of each column:\n",
- m.product_of_each_column(),
- sep="",
- )
- print(
- "Problem 4 clockwise spiral traverse:\n",
- m.clockwise_spiral_traverse(),
- sep="",
- )
- m_rotate_90, m_rotate_180 = m.rotate_90_clockwise_and_180()
- print("Problem 4 rotate 90 clockwise:\n", m_rotate_90, sep="")
- print("Problem 4 rotate 180:\n", m_rotate_180, sep="")
- if __name__ == "__main__":
- test_and_print(None)
- test_and_print([])
- test_and_print("123")
- test_and_print([[]])
- test_and_print([[0]])
- test_and_print([[1, 2], [3]])
- # row=3, col=4
- m1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
- test_and_print(m1)
- # row=4, col=3
- m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
- test_and_print(m2)
- # row=3, col=3
- m3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- test_and_print(m3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement