Matrix structure.
| 4 | |
| 5 | |
| 6 | class Matrix: |
| 7 | """ |
| 8 | <class Matrix> |
| 9 | Matrix structure. |
| 10 | """ |
| 11 | |
| 12 | def __init__(self, row: int, column: int, default_value: float = 0) -> None: |
| 13 | """ |
| 14 | <method Matrix.__init__> |
| 15 | Initialize matrix with given size and default value. |
| 16 | Example: |
| 17 | >>> a = Matrix(2, 3, 1) |
| 18 | >>> a |
| 19 | Matrix consist of 2 rows and 3 columns |
| 20 | [1, 1, 1] |
| 21 | [1, 1, 1] |
| 22 | """ |
| 23 | |
| 24 | self.row, self.column = row, column |
| 25 | self.array = [[default_value for _ in range(column)] for _ in range(row)] |
| 26 | |
| 27 | def __str__(self) -> str: |
| 28 | """ |
| 29 | <method Matrix.__str__> |
| 30 | Return string representation of this matrix. |
| 31 | """ |
| 32 | |
| 33 | # Prefix |
| 34 | s = f"Matrix consist of {self.row} rows and {self.column} columns\n" |
| 35 | |
| 36 | # Make string identifier |
| 37 | max_element_length = 0 |
| 38 | for row_vector in self.array: |
| 39 | for obj in row_vector: |
| 40 | max_element_length = max(max_element_length, len(str(obj))) |
| 41 | string_format_identifier = f"%{max_element_length}s" |
| 42 | |
| 43 | # Make string and return |
| 44 | def single_line(row_vector: list[float]) -> str: |
| 45 | nonlocal string_format_identifier |
| 46 | line = "[" |
| 47 | line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) |
| 48 | line += "]" |
| 49 | return line |
| 50 | |
| 51 | s += "\n".join(single_line(row_vector) for row_vector in self.array) |
| 52 | return s |
| 53 | |
| 54 | def __repr__(self) -> str: |
| 55 | return str(self) |
| 56 | |
| 57 | def validate_indices(self, loc: tuple[int, int]) -> bool: |
| 58 | """ |
| 59 | <method Matrix.validate_indicies> |
| 60 | Check if given indices are valid to pick element from matrix. |
| 61 | Example: |
| 62 | >>> a = Matrix(2, 6, 0) |
| 63 | >>> a.validate_indices((2, 7)) |