Median


#1

What is wrong in this piece of code

1

. ```
2. import math
3. def median(l):
4.     m=0
5.     x = sorted(l)

6.     if(len(x)%2 == 0):
7.        
8.         m= int(len(x)/2 + (len(x)/2)+1/2)
9.     else:
10.         m=int(math.ceil(len(x)/2))
11.     return m
12. print median([4,5,5,4])
13. print median([1,3,2])
14. ```

import math
def median(l):
    m=0
    x = sorted(l)

    if(len(x)%2 == 0):
       
        m= int(len(x)/2 + (len(x)/2)+1/2)
    else:
         m=int(math.ceil(len(x)/2))
    return m
print median([4,5,5,4])
print median([1,3,2])

#2

at no point i see you use indexes to get the values from the list. I would highly recommend to get the middle indexes, and then the corresponding value from the list


#3

Try using 2.0 instead only 2, so you will get a float 4.5 not a 5.
You dont need to initialize m = 0, and dont need to import math too.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.