Python Find the Median of an Array
The median is an important concept in statistics; it represents the middle value of a set of data. For a sorted array, if the length is odd, the median is the middle number; if the length is even, the median is the average of the two middle numbers. Below is an example of finding the median of an array in Python.
Example
def
find_median
(
nums
)
:
nums_sorted
=
sorted
(
nums
)
n
=
len
(
nums_sorted
)
mid
=
n //
2
if
n %
2
==
1
:
return
nums_sorted
[
mid
]
else
:
return
(
nums_sorted
[
mid -
1
]
- nums_sorted
[
mid
]
)
/
2
Example array
nums
=
[
3
,
5
,
1
,
4
,
2
]
median
=
find_median
(
nums
)
(
f
"The median of the array is: {median}"
)
Code analysis:
find_medianThe function accepts an arraynumsas its argument.nums_sorted = sorted(nums)sort the array to obtain an ordered array.n = len(nums_sorted)Get the length of the array.mid = n // 2Calculate the middle position of the array.- If the array length is odd (
n % 2 == 1), return the middle element directlynums_sorted[mid]。 - If the array length is even, return the average of the two middle elements
(nums_sorted[mid - 1] + nums_sorted[mid]) / 2。
Output result:
数组的中位数是: 3
Python3 Examples