Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Median of an Array

Python Find the Median of an Array

Document Object Reference Manual Python3 Examples

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

]

[

mid

]

)

/

2

Example array

nums

=

[

3

,

5

,

1

,

4

,

2

]

median

=

find_median

(

nums

)

print

(

f

"The median of the array is: {median}"

)

Code analysis:

  1. find_median The function accepts an array nums as its argument.
  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 // 2 Calculate the middle position of the array.
  5. If the array length is odd (n % 2 == 1), return the middle element directly nums_sorted[mid]。
  6. 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

Document Object Reference Manual Python3 Examples