Median Help


#1



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


Ok I'm stuck after if statement. I want to know how can i get the 2 median number of the list in the if statement that i've made. Do i use indexing?


def median(lst_middle):
    lst_middle = sorted(lst_middle)
    middle = float(len(lst_middle))
    if middle % 2 == 0:


#2

Have you tried it yet? What is it that you're confused about? The accessing part or getting the middle values?
Also be careful when using the % operator without comparing it to anything. The if statement will always be true.


#3

getting the middle value is what im stuck at. And yes, i forgot to do if middle % 2 == 0:


#4

Ok let's say you have someList = [1, 2, 3, 4] then the middle value would be 2, 3, right? That is somelist[1] and somelist[2]

Let's say we have another otherList = [2, 3, 4, 5, 7, 9, 10, 11] the middle would be 5 and 7 which is otherList[3] and otherList[4]

Do you get the idea? If not then first try to think that the list index starts from 1 instead of 0. Remember that you can think the middle point as half of the numbers.


#5

Right. So if i divide the list in half and -1 will i get 1st middle number?


#6

    if len(lst)==1:
        return lst[0]
    elif len(lst)%2==0:
        middle=float(lst[x]+lst[x-1])/2
    else:
        middle=lst[x]
    
    return middle

With x equal to len(lst)/2


#7

The code passed without doing that.


#8

I dont understand how the equation work. What does float(lst[x]+lst[x-1] do?


#9

Yes, that's right.

It's the sum of the two middle values. The float is so that if you divide 3 by 2 it will return 1.5 instead of 1.0. But you can also make either the dividend or the divisor a float to achieve the same result e.g. 3/2.0


#11

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