15. Median


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.

[4, 4, 5, 5]
Traceback (most recent call last):
  File "median.py", line 17, in <module>
  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.

def median(lst):
    if le%2 == 0:
        mide= le/2
        mede = lst[mide] + lst[mide-1]
        mede /= 2.0
        mid = le/2
        med = lst[mid]


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

     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


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.


[4, 4, 5, 5]


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


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