Finding Median using python 3. Kindly assist


The code below runs perfectly in python 2 but when I run it in python 3 the console returns an error saying : " total=(sorted_list[first]+sorted_list[second])/2.0
TypeError: list indices must be integers or slices, not float"

I wish to know if I missed something and make the code run.Thanks

def median(lists):
    if len(sorted_list)==1:
        return sorted_list[0]
    elif len(sorted_list)%2==0:
        first= len(sorted_list)/2-1
        second= first+1
        return total
        return total
print median([29,23,27,28,25,23])


seems first:

first= len(sorted_list)/2-1

is a float, that is bad, we need integers to access list items. You could just use int() to cast it to a integer, or use // instead of /, which will floor the number (given the length of the list is even, // is safe to use)


Hi, I have used // to floor the number and it worked. Kindly explain what floor means? If I were to use int() instead of // would it be like this:

print (first)


you have used floor before? in python2 / did floor. You don't know what flooring a number means? You round it down. 4.5 becomes 4. It also makes sure the number stays a integer, and not a float

no? As you can see, 2.0 is still a float. int should either hold the entire calculation, or at least the dividing.


I can see the difference now.Thanks


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