# Median

#1

It always shows: Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5
Can you help me?

``````def median(n):
sort = sorted(n)
count = 0
if len(sort)==1:
count = sort[0]
elif len(sort)%2==1:
count = sort[len(sort)/2]
else:
count = (sort[len(sort)/2-1]+sort[len(sort)/2])/2
return count

print median([4,5,5,4]).``````

#2

I hope this helps:

Your code returns 4.5 when you use floats, but 4 when you use integers.

print median([ 4.0, 5.0, 5.0, 4.0]) returns 4.5

#3

It will help to make the program run, but what of the list the SCT tests against? Incorrect code will fail. We cannot fudge the inputs just to guarantee the outputs. That's just not done.

In truth, somebody got codisitis and read way more into the situation than was required. My suggestion would be to go back to the drawing board and simplify this code.

And just to show what we can do with Python,

``return s[m] if n % 2 else float(s[m - 1] + s[m]) / 2``

provided `s` is a list of sorted numbers, `n` is the length, and `m` is the middle index by integer division.

#4

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