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
4 Antworten
+ 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}')
+ 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"
+ 1
Såñtösh I said I don't want to use any module...
0
You should see this post
https://www.sololearn.com/Discuss/2572533/?ref=app