forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedian_matrix.py
38 lines (27 loc) · 738 Bytes
/
median_matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
https://en.wikipedia.org/wiki/Median
"""
defmedian(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 sorted 1D list
linear=sorted(numforrowinmatrixfornuminrow)
# Calculate the middle index
mid= (len(linear) -1) //2
# Return the median
returnlinear[mid]
if__name__=="__main__":
importdoctest
doctest.testmod()