Median logic


#1

When I run the script, I am getting:
"Oops, try again. median([1]) returned 0 instead of 1"

If I comment out the return after the IF and replace it with "Return 1" (troubleshooting step only), then the script moves on to finding the median of [4,5,5,4], and I get the error:
"Oops, try again. median([4, 5, 5, 4]) resulted in an error: 2 is not in list"

I have reviewed the logic deveral times, but cant seem to see where I'm going wrong.

Help?

def median(orig_list):
    sort_list = sorted(orig_list) #put the list in order
    x = len(sort_list)  #the list is x terms long
    if x == 1: 
        return sort_list.index(1) # if list has only 1 item, just return it
    elif x % 2 == 0: # its even, find the middle two terms and average them.
        return (sort_list.index(x/2) + sort_list.index(x/2 +1))/2.0
    else: #it is odd, find the middle term and return it
        return sort_list.index(x/2 + 0.5)

#2

i think the biggest concern for your code is that you seem to misunderstand .index()

.index() gives you the index of the item in list, not to use index to get value:

aList = ['a', 'b', 'c']
print aList.index('a') // 0

#3

THANKS!

OK. I think I got hold of my index issue, modified my code accordingly:

def median(orig_list):
    sort_list = sorted(orig_list) #put the list in order
    x = len(sort_list)  #the list is x terms long
    if x == 1: 
        return sort_list[x-1] # if list has only 1 item, just return it
        #return 1
    elif x % 2 == 0: # its even, find the middle two terms and average them.
        return (sort_list[(x-1)/2] + sort_list[(x-1)/2 +1])/2.0
    else: #it is odd, find the middle term and return it
        return sort_list[(x-1)/2 + 0.5]

I get a new error:
"Oops, try again. median([6, 8, 12, 2, 23]) resulted in an error: list indices must be integers, not float"
I'll keep digging.


#4

Ha!

It was the silly "+ 0.5"" on the last line. Good to go.

Thanks!


#5

A post was split to a new topic: Getting the error -> Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5


#6

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