Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

get median using python

# --------------------- MEDIAN ---------------------

# Dataset for questions -
dataset = [2, 1, 1, 4, 5, 8, 12, 4, 3, 8, 21, 1, 18, 5]

# Finding length of dataset
lenOfDataset = len(dataset)

# Sorting dataset in ascending order
dataset.sort()

# checking the numbers if its even or odd by checking their remainders
# If the number is even, we find 2 middle elements in a list and get their average to print it out
# But if the number is odd, we find the middle element in a list and print it out.
if lenOfDataset % 2 == 0:
    median1 = dataset[lenOfDataset//2]
    median2 = dataset[lenOfDataset//2 - 1]
    median = (median1 + median2)/2
else:
    median = dataset[lenOfDataset//2]

# Printing the median of dataset
print(median)
Source by nbviewer.org #
 
PREVIOUS NEXT
Tagged: #median #python
ADD COMMENT
Topic
Name
6+4 =