Finding Median using python 3. Kindly assist


#1



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


median=[]
def median(lists):
    sorted_list=sorted(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
        total=(sorted_list[first]+sorted_list[second])/2.0
        return total
    else:
        first=len(sorted_list)/2
        total=sorted_list[first]
        return total
print median([29,23,27,28,25,23])


#2

seems first:

first= len(sorted_list)/2-1
print(first)

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)


#3

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:

first=int(len(sorted_list))/2-1
print (first)

#4

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.


#5

I can see the difference now.Thanks


#6

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