Python Find the Median of an Array

Document 对象参考手册Python3 Examples

The median is an important concept in statistics; it represents the middle value of a data set. For an ordered array, if the length of the array is odd, the median is the middle number; if the length of the array is even, the median is the average of the two middle numbers. Below is an example code for 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)
print(f"The median of the array is: {median}")

Code explanation:

  1. find_medianThe function accepts an arraynumsas a parameter.
  2. nums_sorted = sorted(nums)Sort the array to obtain an ordered array.
  3. n = len(nums_sorted)Get the length of the array.
  4. mid = n // 2Calculate the middle position of the array.
  5. If the length of the array is odd (n % 2 == 1), directly return the element at the middle positionnums_sorted[mid]。
  6. If the length of the array is even, return the average of the two middle elements(nums_sorted[mid - 1] + nums_sorted[mid]) / 2。

Output result:

数组的中位数是: 3

Document 对象参考手册Python3 Examples

Other Extensions