1
I’m having a problem on the line index
, because it does not accept float
. But how can I get around it?
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))
You can’t understand your problem. Which error has appeared? On which line? What should this code do?
– Woss
I don’t see how you can return a float when counting the number of indexes in a list, after all it is not possible to have 4.7 indexes, only integers.
– Denis Callau
this is the error that appears: "Typeerror: list indices must be integers, not float expected result: 2, current result: 2" , can’t have a broken index, but for this particular case we need to only divide between the sum of the two middle numbers. when a list has an even number of elements.
– Márcio Feitosa
What exactly do you want?
– Sidon
whenever the list has an even number it must return a float, which is the division between the two numbers in the middle of the list with even number of elements.
– Márcio Feitosa