15 median (i'm stuck!)


#1

def median(mid):
mid.sort()
x = (len(mid) / 2) - 1
b = len(mid) / 2)
for index, item in enumerate(mid):
if len(mid) % 2 == 0:
c = (index[b] + index[x]) / 2
return c
elif len(mid) % 2 != 0:
return index[x]

this is my code. i have no idea why it isn't working, the error i am getting is "median([1]) resulted in an error: argument of type 'int' is not iterable"

can someone help and explain what i did wrong?


#2

A bit more code than necessary, but let's look at what we need, and the rest we can forego.

The function takes a list, and since we are dealing with median, we know we need that list to be sorted so the middle values are at the middle of the list.

    mid.sort()

That sorts the list in place. Now we just need to find the middle of the list. If it is an odd count of elements, that index will be,

    x = len(mid) / 2

In Python, dividing an integer by an integer yields an integer. Now if the list is an even count, then we need the middle two elements, which we will then average. Consider the following...

    [ 1, 2, 3, 4, 5, 6, 7, 8 ]

The length is 8, divided by 2 gives 4. The OP code implies that we want to target index 4 (which is 5) and index 4-1, or 3, which is 4. Added together gives us 9, which if we divide by a float, 2.0 will give 4.5 as the median.

This all boils down to a simple if statement:

    if x % 2:
        return mid[x]
    else:
        return (mdi[x] + mid[x-1]) / 2.0