[SOLVED]: median([4, 5, 5, 4]) returned 4.0 instead of 4.5 but code works in console


#1



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


My code works in a python-console as expected, but the codecademy lies about the results.
Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5

median([4,5,5,4])
4.5


What can i do to finish?

def median(this):
    this.sort()
    if not len(this) % 2 == 0:
        return(this[len(this) / 2])
    else:
        result=int(len(this) / 2)
        return float((this[result-1] + this[result] ) / 2)

Exercise 15: Median - 15. Practice Makes Perfect [python2 and 3 confusion]
#2

The number inside float() is already an integer because nature of / in python 2.0.

4 / 3 -- > 1
4 / 3.0 --> 1.333
To have a decimal value we need to make one of the number a float.


#3

Thanks alot for your reply! The Magic was python2 vs. python3.

~$ python2 median.py
~$ 4.0
~$ python3 median.py
~$ 4.5

I have 'fixed' this with an ' * 1.0' inside the round brackets pre divide.


#4

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