returning indexes of python lists

1

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))
    
asked by anonymous 24.07.2017 / 17:25

2 answers

1

If your intention is to calculate the median of a list:

With numpy:

import numpy
numbers = [1,2,3,4]
numpy.median(numbers)
2.5

Sem numpy

def median(numbers):
    sortlist = sorted(numbers)
    len_numbers = len(numbers)
    index = (len_numbers - 1) // 2
    if (len_numbers % 2):
        return sortlist[index]
    else:
        return (sortlist[index] + sortlist[index + 1])/2.0

median([1,2,3,4])
2.5
    
24.07.2017 / 19:20
1

So I understand you're trying to implement the MEDIANA function.

In this case when the list of numbers has odd length you return the central element, but when the list length is even returns the mean of the two central elements, correct?

If this is your implementation should be:

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:
        mediana = (numbers[hlf-1] + numbers[hlf]) / 2 #Media dos dois elementos centrais
    else:
        mediana = numbers[hlf] #Elemento central
    return mediana

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))
    
24.07.2017 / 19:36