Median: Not able to go to next , even though the output is correct


#1



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

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


For my understanding , code works as expected.
But i am not be allowing to go to next session.
I tried in my spider IDE and it works as expected


def median(n):
    n = sorted(n)
    print (n)
    for i in range(len(n)):
        if len(n)%2 >0:
            x = (len(n)//2)
            return n[x]
        else:
            y = len(n)//2
            x = (n[y]+n[y-1])/2
            return x
print (median([4,5,5,4]))

Output from IDE:
=============
runfile('C:/Users/admin/.spyder-py3/median.py', wdir='C:/Users/admin/.spyder-py3')
[4, 4, 5, 5]
4.5


#2

Your code returns 4. The median for [4, 5, 5, 4] is 4.5.


#3

Thanks for the reply. I have run my earlier code on my spyder IDE which is of
python 3.x version,
It gives me correct result as expected,
Below is the code run o/p from my IDE
runfile('C:/Users/admin/.spyder-py3/median.py', wdir='C:/Users/admin/.spyder-py3')
[4, 4, 5, 5]
4.5

But from the lesson if i run the same piece of code I am getting error:

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

I am not able to understand , why is the difference running of the same code gives error in the lesson


#4

This line:

x = (n[y]+n[y-1])/2

should be

x = (n[y]+n[y-1])/2.0

Without signifying that we are dividing by a float, Python will automatically flatten our result. As it is now, your code only returns non-float integers.

Edit:
Also, why are you running this through a for loop? Seems a bit unnecessary to me.


#5

Is it some thing w.r.t python version which i am using or the IDE framewok which is the root cause of the difference?

Because I use 3.x version , on which even if i try with 2 and not 2.0 it gives me the correct result.


#6

In Python 2.7.13, the version used by Codecademy, all numeric operations will return flat integers unless otherwise specified.


#7

Yes correct, For loop is not necessary.
Thanks for pointing that.
But my earlier query is still alive


#8

As previously stated,

In Python 2.7.13, the version used by Codecademy, all numeric operations will return flat integers unless otherwise specified.


#9

Thanks for the clarification.
Now Onwards, i need to double verify the code on backward release version also.


#11

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