I'm having a problem with the index
line because it does not accept float
. But how can I do to get around this?
def median(numbers):
numbers.sort()#The sort method sorts a list directly, rather than returning a new sorted list
num = len(numbers)
hlf = int(num/2)
if num%2 == 0:
m1 = numbers[:hlf]
m2 = numbers[hlf:]
un = int(m1[-1])
pn = int(m2[0])
middle_index = float((un+pn)/2) #int(len(numbers)/2)
else:
middle_index = int(len(numbers)/2)
return numbers[middle_index]
test1 = median([1,2,3])
print("expected result: 2, actual result: {}".format(test1))
test2 = median([1,2,3,4])
print("expected result: 2.5, actual result: {}".format(test2))
test3 = median([53, 12, 65, 7, 420, 317, 88])
print("expected result: 65, actual result: {}".format(test3))