Problem of median


#1




def median(item):
    total = 0
    for i in item:
        total += 1
    return total
    if total % 2 == 0:
        item = sorted(item)
        s = (item[total / 2] + item[total / 2 + 1]) / (2.0)
    if total % 2 != 0:
        item = sorted(item)
        s = item[(total + 1) /2]
    return s


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


I don't know where the mistake is,help me please,thank you


Replace this line with your code.


#2

a function ends the moment a return keyword is reached

so huge part of your code is never reached


#3

It means that my code is too large to complete compute?


#4

no, it means that the code after return is never executed, your function ends here:

return total

#5

then how do I change my code to let the rest run


#6

given the return keyword causes the function to end, removing the return keyword sounds like a good idea


#7

I just contain the return in the last line?


#8

given you need to return the median value value, yes, i would keep return s at the last line


#9

ok,I'll try ,thank you


#10

def median(item):
if len(item) % 2 == 0:
item = sorted(item)
s = (item[len(item) / 2] + item[(len(item) / 2) + 1]) / (2.0)
if len(item) % 2 != 0:
item = sorted(item)
s = item[len(item) / 2]
return s
I am so sorry to bother you again,it returns 5.0 not 4.5,I don't understand what's wrong


#11

no bother, that is what the forum is for :wink:

well, agree that the list ([4,4,5,5], (sorted)) is 4 long? and that the indexes are: 0, 1, 2 and 3? so length divided by 2 give index 2, so right middle value, and length divided by 2 + 1 gives right value? This should be left middle value, so -1, not +1


#12

Oh,my! The index begins at 0 not 1!Thank you so much!I've got it!


#13

yes, lists are zero index based :wink:

Good you sorted it out :slight_smile:


#14

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