Median (Almost got it right but for 1 error!)


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096


Error: "Oops, try again. median([1]) returned [1] instead of 1"


def median(n):
    ready = []
    ready.append(sorted(n))
    length = len(ready)
    if length % 2 == 0:
        mid_1 = length / 2
        middle_1 = ready[mid_1] 
        mid_2 = mid_1 + 1
        middle_2 = ready[mid_2]
        median = (middle_1 + middle_2) / 2.0
        return median
    else:
        mid = length / 2
        median = ready[mid]
        return median


#2

It says you returned A instead of B
Do you see the difference between A and B? What action would you need to perform to turn A into B?
Would you say it that it would help to see what it's doing as it runs? You can use print statements to inspect the values it's using, you can make it describe to you what it is doing step by step


#3

Well, I tried. It wouldn't allow me to print because of the error.

Is it because I am creating a list within a list?

i.e. ready = [[4, 5, 5, 4]]. Something like that?


#4

If you print before the exception occurs they'll still come out.. or if you mean codecademy's message then that doesn't prevent your code from running first

If you don't call your function then obviously it won't be doing any printing either

Are you asking whether it is or whether it should or shouldn't be that way?
Prints can tell you whether that is the case
Referring to what actions it's supposed to do can tell you whether it should be (motivate why it would or wouldn't be a list inside another list) ie. do you want to be using a list of numbers or a list of lists of numbers? I don't think you need me for that, rather you just have to formulate the question and consider it


#5

To answer your question: No, I don't want a list within a list. And I was doing exactly that, which I later rectified as given in the code below.

The other mistake I had in my code was that I overlooked the fact that indices start from 0 and that I had to make that correction when I wanted to use the actual values in the list for finding out the median value in the list.

Here is the corrected code: (This works. :slight_smile: )

def median(n):
    n = sorted(n)
    length = len(n)
    
    if length % 2 == 0:
        mid_1 = length / 2
        middle_1 = n[mid_1 - 1]
        mid_2 = mid_1 + 1
        middle_2 = n[mid_2 - 1]
        median = (middle_1 + middle_2) / 2.0
        return median
    else:
        mid = length / 2
        median = n[mid]
        return median
        
print median([4,5,5,4])

#6

Thanks for your time! It really had me thinking and observing more carefully. :slight_smile:


#7

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