15/15 median problem


#1

Hello there
I just finished everything up to 15/15. I figured a way out to do that but it won't work.


the problem is that the if loop
if i == lst[halfl] :
acct = (lst[halfl] + lst[halfl - 1]) / 2.00
media += acct
gets executed twice when the there are two numbers with the same value. How can I fix that or has somebody got a better solution. Thank you very much.
Joe


#2

Question, why are you looping through the list?

It should only get the median numbers,

Example:

def median(num_lst):
    if len(num_lst) % 2 != 0:
        return num_lst[int(len(num_lst) / 2)]
    else:
        return (num_lst[int(len(num_lst) / 2)] + num_lst[int(len(num_lst) / 2) - 1]) / 2.0

If you loop through your list you will be proforing the task more than necessary.


#3

Sorry if I'm convoluting the answer stream, but my code below is generating the error, " Oops, try again. median([6, 8, 12, 2, 23]) returned 2 instead of 8 " and I have no idea why.. Should I sort the numbers and then return the middle value? What are methods of going about that?

def median(lists):
med = 0
if len(lists)%2 == 0:
med = (lists[len(lists)/2] + lists[(len(lists)/2) + 1])/2.0
elif len(lists) == 1:
return lists[0]
else:
med = lists[(len(lists)+1)/2]
return med