Calculate the median of a sorted matrix. Args: matrix: A 2D matrix of integers. Returns: The median value of the matrix. Examples: >>> matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]] >>> median(matrix) 5 >>> matrix = [[1, 2, 3], [4, 5,
(matrix: list[list[int]])
| 4 | |
| 5 | |
| 6 | def median(matrix: list[list[int]]) -> int: |
| 7 | """ |
| 8 | Calculate the median of a sorted matrix. |
| 9 | |
| 10 | Args: |
| 11 | matrix: A 2D matrix of integers. |
| 12 | |
| 13 | Returns: |
| 14 | The median value of the matrix. |
| 15 | |
| 16 | Examples: |
| 17 | >>> matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]] |
| 18 | >>> median(matrix) |
| 19 | 5 |
| 20 | |
| 21 | >>> matrix = [[1, 2, 3], [4, 5, 6]] |
| 22 | >>> median(matrix) |
| 23 | 3 |
| 24 | """ |
| 25 | # Flatten the matrix into a sorted 1D list |
| 26 | linear = sorted(num for row in matrix for num in row) |
| 27 | |
| 28 | # Calculate the middle index |
| 29 | mid = (len(linear) - 1) // 2 |
| 30 | |
| 31 | # Return the median |
| 32 | return linear[mid] |
| 33 | |
| 34 | |
| 35 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected