15. median


#1



Whats wrong

def median(lst):
    lst.sort()
    k = len(lst)
    l = k/2
    if k % 2 != 0 :
        return lst[l]
    else:
        return (lst[l-1] + lst[l])/2


#2

What error is it giving you?


#3

you're using l in "return lst[l]"

If a list is length of 7, l would be equal to 3.5
there is no such index within an array equal to a decimal.

try the following

import math

def median(list):
    list.sort()
    list_len = len(list)
    middle = math.floor(list_len / 2)
    [your if/else]

math.floor will take X.Y and strip away the .Y leaving you with X so instead of 1.5, you get 1


#4

I already solve that and this is my code who worked great
def median(lst):
lst.sort()
k = len(lst)
l = k/2
if k % 2 != 0 :
return lst[l]
else:
return (lst[l-1] + lst[l])/2.0

and Thank you


#5

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