def median(lst):
    lst = sorted(lst)
    length = len(lst)
    summa = 0
    if length % 2 != 0:
        return lst[(length/2)-1:(length/2)]
    elif length == 1:
        return lst[0]
        for i in lst[(length/2)-1:(length/2)+1]:
            summa += i
        return float(summa)/2

Oops, try again. median([1]) returned [] instead of 1


for [1] the if condition is true. So, this is the code that runs. Here you use list slicing, which will give you a list. Why list slicing? It makes very little sense given you want an number as result

for odd list you need the middle index and use this middle index to retrieve the middle value


What can I use there instead of slicing to get a number, except "for loop"?


well, you can use square brackets to retrieve a value from a list:

aList = [1,2,3]
print aList[1] # will retrieve value (2) from index 1

what you did:

aList = [1,2,3]
print aList[0:1] # will give [1]

is list slicing, see the difference?

As for lists with even lists, you need to calculate the middle two indexes, retrieve the values of this indexes, add them together, and divide them by 2


Thanks, I got this in a couple of seconds after I asked that stupid question


AWS (amazon hosting) was hours offline because of a typo (!!!), programmers just sometimes make silly mistakes, and then its then so obvious staring them in face, and just don't see it. It happens to the best

You think you can figure it out? If you need more help, post:

an updated version of your code
your question
error message

and i will help you further, but its better if you figure it out yourself (you will learn more from it, not that i don't want to help)


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