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