15. Median


#1



What am i doing wrong or missing and why?
Error : Oops, try again. median([1]) returned [1] instead of 1


def median(lst):
    lst = sorted([lst])
    print lst
    if len(lst) % 2 == 0:
        med = (lst[len(lst) / 2] + lst[len(lst) / 2-1]) / 2
    else:
        med = lst[(len(lst)-1) / 2]
    return med
print median([1, 2, 3, 4, 5, 6])


#2

you have this beautiful line of code here:

print lst

which, will nicely show that if you pass [1] into the function, print lst will print [[1]]. You made a multi-dimensional list, which is something i wouldn't do. You can simple sort the list like so:

lst = stored(lst)

this way you will not get a multi-dimensional list. now, this will resolve your current issue, this will give you a new error, try to solve this problem self first. If you need more help, post an updated version of your code


#3

So it gav e me a new error btu i still don't know what'a happening.
code:

    lst = sorted(lst)
    if len(lst) % 2 == 0:
        med = (lst[len(lst) / 2] + lst[len(lst) / 2-1]) / 2
    else:
        med = lst[(len(lst)-1) / 2]
    return med
print median([1, 2, 3, 4, 5, 6])

Error
Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5 While console output is 3


#4

if your list is 4,4,5,5 (after sorting), you get med = 5 + 4 /2

but there is catch, a integer (9) divided by a integer (2) returns a integer. so 9 / 2 = 4.5 but since both 9 and 2 are integers, the number gets floored. To overcome this problem, either divide by a floating number (decimal number, 2 is the same thing as 2.0) or use float() to cast the outcome to a float


#5

So like this?

def median(lst):
    lst = sorted(lst)
    if len(lst) % 2 == 0:
        med = float((lst[len(lst) / 2] + lst[len(lst) / 2-1]) / 2)
    else:
        med = float(lst[(len(lst)-1) / 2])
    return med
print median([1, 2, 3, 4, 5, 6])

#6

well, does it work? If it does, the code is very likely correct


#7

Nope.Result is now a decimal btu it doesn't work.Changed the list,result changed but same.


#8

but the float cast is wrong, you now cast 4 to 4.0, you should either cast 9 (the sum of the two list items) or 2 to a float (in which case i would just use 2.0


#10

def median(lst):
    lst = sorted(lst)
    if len(lst) % 2 == 0:
        med = (lst[len(lst) / float(2)] + lst[len(lst) / 2-1]) / float(2)
    else:
        med = lst[(len(lst)-1) / float(2)]
    return med
print median([4, 5, 5, 4])

I don't know what am i doing wrong.


#11

when you access a list item by index, those numbers should be integers.... the only place you need float() is at the very end of your code in the if statement:

.... / float(2)

#12

Worked.Thank you so much.But why in the result i had 4.5 but still it was wrong?


#13

you're welcome, no idea, your latest code gave me an error message. But now you fixed it :slight_smile: