find the median of all elements in an array in python

To find the median of all elements in an array in Python, you can use the median function from the statistics module (Python version 3.4 and newer).

First, you need to sort the array in ascending order using the built-in sort function. Then, you can pass the sorted array to the median function to get the median.

Here's the code:

main.py
import statistics

arr = [3, 1, 4, 2, 5]  # Example array

arr.sort()  # Sort the array in ascending order

median = statistics.median(arr)  # Find the median of the sorted array

print(median)  # Output: 3
207 chars
10 lines

Alternatively, if you don't want to use the statistics module, you can manually calculate the median by finding the middle element(s) of the sorted array:

main.py
arr = [3, 1, 4, 2, 5]  # Example array

arr.sort()  # Sort the array in ascending order

n = len(arr)
middle = n // 2  # Integer division for Python 3

if n % 2 == 0:
    # If the array has an even number of elements, take the average of the middle two
    median = (arr[middle - 1] + arr[middle]) / 2
else:
    # If the array has an odd number of elements, take the middle element
    median = arr[middle]

print(median)  # Output: 3.0
437 chars
16 lines

Note that in the second implementation, we used n // 2 instead of (n + 1) // 2. This is because Python uses floor division by default, so we don't need to add 1 for odd-length arrays.

gistlibby LogSnag