Skip to content

Commit 922d6a8

Browse files
BamaCharanChhandogipre-commit-ci[bot]cclauss
authored
add median of matrix (#9363)
* add median of matrix * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix formating * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Apply suggestions from code review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent d743497 commit 922d6a8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

matrix/median_matrix.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Median
3+
"""
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__":
36+
import doctest
37+
38+
doctest.testmod()

0 commit comments

Comments
 (0)