Median, is the code wrong again?


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096


hello again, I am stuck with median now, below are my code, although I have noticed the rule that in python string and list are indexed from zero, but I still have trouble in calculating the median. The message keeps telling me that [4, 5, 5, 4] cannot apply to my code. But I really cannot figure out where the problem is.


So, if you can help me with this problem, I would be more than glad!


def median(n):
    sorted(n)
    if len(n) % 2 != 0:
        med = n[(len(n) - 1) / 2]
    else:
        med1 = n[(len(n) / 2) - 1]
        med2 = n[(len(n) / 2)]
        med = (med1 + med2) / 2
    return med


#2

there are two problems, you sort the list, but don't store the sorted list anywhere (in a variable)

and for [4,5,5,4] the two middle values of the sorted list are 4 and 5, add them together and you get 9. 9 / 2 is 4, pyton will floor/round down if the division involves two integers, so you will need to use a float in the division


#3

Oh my! I totally forgot about storing the sorted values in a variable, maybe I have been used to using another tool,hhhhh.
def median(n):
n = sorted(n)
if len(n) % 2 != 0:
med = n[(len(n) - 1) / 2]
else:
med = (n[(len(n) / 2) + 1] + n[(len(n) / 2)]) / 2.0
return med
this is the new code, but it still shows the same problem, could you please clarify a little bit more clearly?
sorry for bothering you again!


#4

OK, I've figured out where my problem is, sorry for bothering you!


#5

#6

good you figured it out :slight_smile: which is better then me telling you