Median


#1



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


Oops, try again. median([4, 5, 5, 4]) returned 7.0 instead of 4.5


Hi! Stuck in this one, please help me realize what i'm doing wrong. Thank you.


def median(lst):
    sort=sorted(lst)
    even_index=lst[len(lst)/2]
    even_index2=even_index-1
    if len(lst)%2==0:
        return even_index+even_index2/2.0
    elif len(lst)<=1:
        return len(lst)
    else:
        return even_index
    lst.append(sort)

print median([1,2,3])


#2

even_index doesn't contain a index, it contains a value, so you can't use it to calculate even_index2


#3

Hey stetim. Can you elaborate more, please? I thought the exercise was asking for the average of the value in the middle of the list. I'm confused :confused:


#4

yes, but you have a variable (even_index) which contains a value (5) from the list, not the index (2), so you can't use even_index to calculate even_index2


#5

Oh i get it, that's a step forward to the solution... but i've been thinking and all i could come up with was:

def median(lst):
sort=sorted(lst)
even_index=lst[0:]/2
even_index2=even_index-1
if len(lst)%2==0:
return even_index+even_index2/2.0
elif len(lst)<=1:
return len(lst)
else:
return even_index
lst.append(sort)

print median([1,2,3])

Got this error: Traceback (most recent call last):
File "python", line 13, in
File "python", line 3, in median
TypeError: unsupported operand type(s) for /: 'list' and 'int'


Even if the ''lst[0:]/2" thing worked, i have no idea how i could access its value to the sum part. :confused:

Edit: Oh geez, just noticed that i've basically done the same mistake than before lol
I'm not in my best day as you can see.

Edit 2: That's the best i came up with mate:

def median(lst):
    sort=sorted(lst)
    even_index=len(lst)/2
    even_index2=even_index-1
    value=lst[even_index]
    value2=lst[even_index2]
    if len(lst)%2==0:
        return value+value2/2.0
    elif len(lst)<=1:
        return len(lst)
    else:
        return value
    lst.append(sort)

print median([1,2,3])

Got this error though: Oops, try again. median([4, 5, 5, 4]) returned 7.5 instead of 4.5


#6

two problems, here:

even_index=len(lst)/2

you use the unsorted list, the median values are the two middle values of sorted list

and order of operations, division will go first:

5 + 5 / 2.0

5 + 2.5
`
you don't want this, you want to get sum first, so use brakcets


#7

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