Median


#1


Hi, Guys. Can't figure out whats wrong. Check working codes in other threads and seems that is no difference but my code does not work. Give an error:
Oops, try again. median([1]) returned -1 instead of 1

def median(x):
    med = 0
    x = sorted(x)
    
    index1 = len(x) / 2
    index2 = len(x) / 2 - 1
    
    if index1 % 2 == 0:
        med = index1 + index2 / 2
    else:
        
        med = len(x) / 2
    
    return med

Thanks


#2

this line is confusing:

if index1 % 2 == 0:

index1 does not contain the length of the list. I would personally check if the length of the list is odd or even.


#3

2 posts were split to a new topic: Median


#4

Thanks! fix it, but now get error:
Oops, try again. median([1]) returned 0 instead of 1

def median(x):
    med = 0
    x = sorted(x)
    
    index1 = len(x) / 2
    index2 = len(x) / 2 - 1
    
    if len(x) % 2 == 0:
        med = (index1 + index2) / 2
    else:
        
        med = len(x) / 2
    
    return med