15. Median


#1



The error message is median([6, 8, 12, 2, 23]) resulted in an error: list indices must be integers, not float, and I don't know why it wants an integer instead of a float.


def median(lists):
    lists = sorted(lists)
    if len(lists)%2 == 0:
        med = (lists[len(lists)/2] + lists[(len(lists)/2)-1])/2.0
    else:
        if len(lists) < 2:
            med = lists[0]
        else:
            med = lists[len(lists)/2 + 0.5] 
    return med
    print med


#2

Let's say the length of the list is 4, this would result in 2.5, which is not a valid index of a list.


#3

Well I tried to make it so it only does that code when it is an odd number.


#4

Then I would change it into (len(list) + 1)/2


#5

Not sure if this one is solved yet. why not throw the index query inside an int()?

lists[int(len(lists)/2 + 0.5)]

that should convert any index reference to an integer. there might be a more efficient way.


#6

The thing he wants to accomplish here is that if you have a length of 5 for instance, you return the middle element, 2.
You can just do list[len(list)/2] for thath.


#7

Working code :slight_smile:...>

def median(li):
    li.sort()
    
    if len(li) % 2 == 0 :    # Here list is  paire  2,4,8
        return float((li[(len(li) / 2) - 1] + li[len(li) / 2 ]))/2
        
    else:   # here list is impaire 3,5,7
        return li[len(li) / 2]

> # examples :

print mediane([2,4,5,4,7,8])        # paire

# Result: 2 4 4 5 7 8 --> 4/5 --> 4.5

print mediane([98,74,5,10,1,3,77])   #impaire

# Result: 1 3 5 10 74 77 98 --> 10

#8

print mediane([2,4,5,4,7,8]),print mediane([98,74,5,10,1,3,77])为什么要多一个e啊?


#9

Hi, am having a bit of trouble with my code on this one and wondering if you could kindly help me out. I tried to put it together in a logical way, but it keeps giving me the wrong median..

def median(lisst):
    sortedl = sorted(lisst)
    length = len(lisst)
    #even
    lower_bound = sortedl[(length/2)-1]
    upper_bound = sortedl[(length/2)]
    #odd
    median_location = (length*2 - 1)/2
    if length %2 == 0: # if list is even
        med = (lower_bound + upper_bound)/2
    else:
        med = sortedl[median_location]
    return med
print median([2,4,5,6])

#10

it did n't work for me