15. Median


#1




I have a problem because I've coded my function on my own text editor and it tells me that there's a problem. But in the site it tells me that my code is right.

OUTPUT :
[4, 4, 5, 5]
2.0
Traceback (most recent call last):
  File "median.py", line 17, in <module>
    print(median([4,5,5,4]))
  File "median.py", line 8, in median
    mede = lst[mide] + lst[mide+1]
TypeError: list indices must be integers or slices, not float


I personally use the last version of Python.


CODE : 
def median(lst):
    list.sort(lst)
    le=len(lst)
    if le%2 == 0:
        mide= le/2
        mede = lst[mide] + lst[mide-1]
        mede /= 2.0
        return(mede)
    else:
        mid = le/2
        med = lst[mid]
        return(med)


#2

this code will work fine in python2, not in python3. why? division was changed, here:

else:
     mid= le/2

lets say the length of our list is 5, then we have:

5 / 2 = 2 # python2 
5 / 2 = 2.5 # python3

the number gets no longer floored in python3 when dividing two integers, instead you will get if a float.

the solution is simply, use floor division:

5 // 2

the same problem here:

mide= le/2

this will now also result in a float, where lists indexes should be integers


#3

Thanks for your answer, I saw it with my Output when I changed it, I was wondering how I would be able to get non-floored numbers coding median in python3.

OUTPUT :

[4, 4, 5, 5]
5.0

#4

i do hope you know now, python3 doesn't floor the numbers by default so you can use the division operator.


#5

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