Median - item #


Link to exercise

"Oops, try again. median([6, 8, 12, 2, 23]) returned 6 instead of 8"

I'm expecting my code to append the middle item of my numbers input into my med list. Which means I would need (len(list) - 1) % 2 in order to get the middle item number for an odd number of items. However, my code appears to be returning item[1] instead of item[2] in an item list with a length of 5. Not really understanding why this is happening. I would appreciate your help.

def median(numbers):
    med = []
    srt = sorted(numbers)
    if len(srt) % 2 == 0:
        mid1 = (len(srt) % 2) + 1
        mid2 = len(srt) % 2
        medi = (numbers[mid1] + numbers[mid2]) / 2.0
        med.append(numbers[(len(srt) - 1) % 2])
    for item in med:
        return item


This is, in my opinion only complicating matters. The median is a single value, not a list object. We really only need three working variables, one for length, one that is half of that (cast to integer), and one that is the sorted list. All operations can be performed with just these three objects.


Wow I feel like a doofus...proof that coding while tired isn't very effective!
Not only was I trying to return items from my numbers[] as opposed to my sorted list srt[], but I was also using the module(%) to try and divide(/) my length to find the list item. Thanks for the help mtf, case closed.

def median(numbers):
srt = sorted(numbers)
length = len(srt)
print srt
if length == 1:
return 1
elif length % 2 == 0:
mid1 = (length / 2) - 1
mid2 = length / 2
medi = (srt[mid1] + srt[mid2]) / 2.0
return medi
elif length % 2 == 1:
media = srt[(length - 1) / 2]
return media


Still see some things I would do differently. Did you pass the exercise?

When you finish the Python track, come back to this module and take another crack at all the exercises. (Save your work and reset the lesson for a do over.) Test your skills early and often until you are really comfortable with the concepts and constructs and are able to create a plan.when you start doing projects of your own.


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