[SOLVED ✔️] What is the best pythonic way to find the median ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[SOLVED ✔️] What is the best pythonic way to find the median ?

I wanna know the best way to find the median of given list of numbers without using any module I know we can find it using numpy >>>import numpy as np >>>np.median(data) but I don't want to use any module please kindly understand... My attempt : https://code.sololearn.com/cDD5NyEJsq8q/?ref=app

6th Dec 2020, 4:31 PM
Ratnapal Shende
Ratnapal Shende - avatar
4 Answers
+ 10
Here is code that calculates the mean and the median: inp =[9, 10, 12, 13, 13, 13, 1, 15, 16, 16, 18, 22, 23, 24, 24, 2] print(f'mean = {sum(inp) / len(inp):.2f}') inp_sorted = sorted(inp) pos = len(inp_sorted)//2 if len(inp_sorted)%2 != 0: median = inp_sorted[pos] else: median = sum(inp_sorted[pos-1:pos+1])/2 print(f'median = {median:.2f}')
6th Dec 2020, 8:04 PM
Lothar
Lothar - avatar
+ 4
Your code looks find. I would like to point out just 2 things: a) It only works if x is an already sorted list. b) If x has an even number of elements, you can output "both median values" (as you do) or the "mean of the 2 midst values"
6th Dec 2020, 5:15 PM
Lisa
Lisa - avatar
+ 1
Såñtösh I said I don't want to use any module...
6th Dec 2020, 4:40 PM
Ratnapal Shende
Ratnapal Shende - avatar
6th Dec 2020, 4:37 PM
Sâñtôsh
Sâñtôsh - avatar