15/15 Having some problems


#1

Check my code please, what's wrong?

def median(x):
x=sorted(x)
l=len(x)
if l!=1:
if l%2!=0:
return ( x[(l+1)/2 ] )
else:
num1=x[int(-1+l/2)]
num2=x[int(l/2)]
return ((num1+num2)/2)
else:
return (x[l-1])


#2

try this. Same thing just made some changes

def median(x):
    x = sorted(x)
    
    if(len(x)%2 !=0):
        
        return x[(len(x)/2)]
        
    else:
        num1 = x[len(x)/2]
        num2 = x[(len(x)/2)-1]
        
        return (num1 +num2)/2.0
        
print median([1,2,3,4,3,2,4,5,6,7,3,2,3])

You can also test it out here

Click to go to labs


#3

def median(numbers):
numbers.sort()
if len(numbers) > 1:
if len(numbers) % 2 == 0:
mid = numbers[len(numbers)/2] + numbers[len(numbers)/2 -1]
return float(mid)/2

    else:
        return numbers[len(numbers)/2]
else:
    return numbers[0]

#4

this one works as well:

def median(l):
    ns = sorted(l)
    lns = len(ns)
    med=float((ns[(lns-1)/2]+ns[lns/2]))/2
    return med

print median([1,2,3,4,3,2,4,5,6,7,3,2,3])