Median


#1



Hi, I don't understand why isn't this working. I'm not much concentrated so this may be just all wrong.Please help me, thanks


This was the error message:
Oops, try again. median([1]) resulted in an error: 'int' object has no attribute 'getitem'


def median(x):
    final = 0
    sorted(x)
    if len(x) % 2 == 0:
        return final[len(x)/2]+final[len(x)/2+1] / 2
    else:
        return final[len(x)-1/2+1]


#2

__getitem__ is the method that corresponds to the []-operator. Your error message says that an integer has no such method, which makes sense, an integer isn't indexable. Where do you use the []-operator in your code? Is it being used on an integer? What should it be used on?

Also note that you while you do sort x, you don't save the sorted result anywhere, so the sorting of x has no effect in your code.


#3

And keep the order of operations in mind. len(x)-1/2+1 is just len(x), I think. -1/2 will evaluate to -1.


#4

In Python 2,

len(x) - 1/2 +1    # 1/2 gets evaluated first
len(x) - 0 + 1     # the quotient is an integer
len(x) + 1

which is probably not the result we are hoping for. What I believe the member is attempting is this:

(len(x) - 1) / 2 + 1

Since Python 2 casts integers from integer division, this whole expression can be reduced to just,

len(x) / 2

9 / 2 == 4   # the median index of a sample with length of 9

#5

I did this now:

def median(x):
    l = sorted(x)
    one = 0
    two = 0
    average = 0
    final = 0
    if len(l) % 2 == 0:
        one = l[len(l)/2]
        two = l[len(l)/2 + 1]
        average = float(one + two) / 2
        return average
    else:
        final = l[len(l)/2]
        return final

The error was: Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5


#6

Find out how it got the answer 5.0 and compare what it did with how you'd be doing it manually


#7

Consider:

[ ] [ ] [ ] [ ] [ ] [ ]
 0   1   2   3   4   5

length is 6, 6 / 2 is 3. Notice the index 3 is actually the higher of the two middle elements?

len(l) / 2 - 1

is the other middle element.


#8

thank you! This is working now. I totally forget about the way this worked :stuck_out_tongue:


#10

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