Python: Practice makes Perfect: Lesson 15: Median


#1

I am currently busy with the practice makes perfect lesson of the python course, and I’m stuck in the last lesson, median.
The input of the median script is a list. it needs to be sorted and return the median.

This is my script:

def median(a_list):
  new_list = sorted(a_list)
  if len(new_list) % 2 == 0:
    middle = new_list[int(len(new_list)/2.0)-1:int(len(new_list)/2.0)+1]
    median = float(sum(middle)/len(middle))
  else:
    median = float(new_list[int(len(new_list)/2)])
  return median

But it throws this error:

median([4, 5, 5, 4]) returned 4.0 instead of 4.5

However, when I run this in for example Rodeo (a Python IDE), it simply gives back 4.5.
I was wondering how this could be? Is there a difference in python?


#2

just covered the exact same problem here:


#3

Thanks for your answer, @stetim94. I thought this might be a problem, that’s why I added /2.0 in my code and added the float() function. Do you know then how I can change my code that it does work in the codecademy tutorial?


#4

but look where you added the 2.0:

middle = new_list[int(len(new_list)/2.0)-1:int(len(new_list)/2.0)+1]

we need integers (list indexes are always integers), which is why you use int(), so using 2.0 at that point, doesn’t make much sense

the problem is here:

median = float(sum(middle)/len(middle))

yes you use float() but after the division (when the rounding down already occured) you cast to float

that is why i was very careful with my words:

the division should involve a float

your division doesn’t involve a float, you cast to float after the division


#5

Ok, great! I understand the problem now, so if I would make one of them a float, changing it to:

median = float(sum(middle))/len(middle)

then it would work :smiley:
Thank you very much!


#6

assuming the rest of your code is correct, yes it should work :slight_smile:


#7

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