Median


#1

Hello, this is the code I wrote:

def median(a_list):
    b_list = sorted(a_list)
    if len(b_list) % 2 == 0:
        a_sum = b_list[len(b_list)/2] + b_list[len(b_list)/2 +1]
        a_answer = a_sum/2
        return a_answer
    else: 
        b_sum = b_list[len(b_list)/2]
        b_answer = b_sum/2
        return b_answer
print (median[1,2,3,4])

and I keep getting a TypeError: 'function' object has no attribute 'getitem'

What is wrong in my code?
Thanks in advance! :slight_smile:


#2

is caused by,

median is the function; [1,2,3,4] is the subscript. Function calls use () to wrap the arguments.

median([1,2,3,4])

Now we get to another problem. Your function returns 3 when it should return 2.5.

Aside:

Can you make your code simpler and more readable by caching repeated expressions?


#3

Thanks! So I deleted the print part
Also, I just realized I shouldnt have this: b_answer = b_sum/2 divided by 2,
So I changed it too.
Now my code is;

And I got the error:
Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5

What is it now?


#4

Ok, I got it:


#5

Good job returning a float. Now if I may comment on this... 2 is a counting number, as in, an integer. Casting an integer to a float doesn't really seem logical, even though it works for this situation. Your reader may be scratching their head. Why not declare the number we might expect to be a float using an explicit declaration?

a_answer = float(a_sum) / 2

There is still the issue of repetition that can be cleaned up for the sake of simplicity. The are four instances of len(b_list) that could be cached:

n = len(b_list)

Now your code will look like the following:

def median(a_list):
    b_list = sorted(a_list)
    n = len(b_list)
    if n % 2 == 0:
        a_sum = b_list[n / 2] + b_list[n / 2 + 1]
        a_answer = float(a_sum) / 2
        return a_answer
    else: 
        b_sum = b_list[n / 2]
        b_answer = b_sum / 2
        return b_answer

This brings us to one other tiny issue. In an even length list,

    items = [7, 4, 6, 2, 9, 3, 5, 2]

    n = len(items)
    m = int(n / 2)
    print m          # 4

Notice that idex [4] is in the upper half of the list? The corresponding data point is to the left of that one, meaning m - 1, not m + 1.


#6

I understand, usually I am so relieved that I got the right answer that I don't think about
being less repetitive and writing in a more effective way, but I really should
Thank you again


#7

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