-1

I'm trying to find the median in a given list but keep getting the wrong answer. What am I missing in my code below?

def median(x):
x = sorted(x)
final = 0
position = (len(x) + 1)/2
if (len(x) + 1) % 2 == 0:
    final = x[position - 1]
else:
    final = (x[position - 1] + x[position])/2
return final
triplepla1
  • 25
  • 1
  • 1
  • 3
  • Are you using python 2 or 3? You need integer division, but might not be using it. – Carl Shiles Jun 16 '17 at 16:00
  • duplicate of https://stackoverflow.com/a/24101534/5660284 – Equinox Jun 16 '17 at 16:01
  • your function does not have proper indentation. Python has mandatory indentation. everything beneat the def keyword that is part of the function should be indented. Moreover you should be using // for integer division if this is python 3. – Matthew Ciaramitaro Jun 16 '17 at 16:01

2 Answers2

0

Your issue is that you are not using integer division and thus are vetting invalid answers at points in your program. The line beginning with position needs to become:

position = (len(x) + 1)//2

The double division sign will make it integer division and you will no longer get errors when trying to put floats as array values.

JoshKopen
  • 940
  • 1
  • 8
  • 22
0

This code should produce the correct result in Python 3 by employing integer division.

def median(x):
  x = sorted(x) #sort list
  final = 0 #confusing var name. try res
  position = (len(x) + 1)//2 #integer division forces the index to be an int
  if (len(x) + 1) % 2 == 0: #should use len(x) % 2 == 1 for efficiency
    final = x[position - 1] #set result to median of array
  else:
    final = (x[position - 1] + x[position])/2 #set result to median of array
  return final

print(median([1,3,2,5]))

In python 2 you could use floating point division instead of integer division and you would get the same result (though just use integer to be safe) Except the division in the else block should be over a float to force it to return a float.

As in:

  if (len(x) + 1) % 2 == 0: #should use len(x) % 2 == 1 for efficiency
    final = x[position - 1] #set result to median of array
  else:
    final = (x[position - 1] + x[position])/2.0 #set result to median of array
  return final

If you want the program to be dually compatible with both versions you must employ both of these changes

Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27