# Median

#1

will anybody help me to find an error in the below code?
the console shows an error like..
"oops median returned 4 instead of 4.5" but in other console it is running fine.

def median(a):
a.sort()
d=(len(a)+1)//2
e=len(a)//2
if len(a)%2!=0:
return a[d-1]
else:
return (a[e-1]+a[e])/2
print(median([4,5,5,4]))

#2

Well, even in another console, you won't still get 4.5. You should return the float of this:

and here:

Make sure in the last above, /2 is outside the float.

I hope this helps!

#3

Thank u...... by the way but i found my problem where it was.. actually "/" is a float division i thought dividing (a[e-1]+a[e]) by(/) 2 will give the float value by default but when i suffixed (.0) after 2 then it gave float value..and answer came 4.5 .

if you try in another console without giving float while doing float division it will give float value by default and i got the same answer in other console.

#4

In Python 3, yes it is by default. In Python 2, integer operations always yield an integer.

13 / 7  == 1

float(13) / 7 = 1.8571428571428572

so,

return float( a + b ) / 2

where a and b are your expression above.

#6

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