Skip to content
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions matrix/median_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
https://en.wikipedia.org/wiki/Median
"""


def median(matrix: list[list[int]]) -> int:
"""
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, 6]]
>>> median(matrix)
3
"""
# Flatten the matrix into a 1D list
linear = [num for row in matrix for num in row]

# Sort the 1D list
linear.sort()

# Calculate the middle index
mid = (0 + len(linear) - 1) // 2

# Return the median
return linear[mid]


if __name__ == "__main__":
import doctest

doctest.testmod()