15/15 error


#1


where is my error now?


#2

def median(a):
n = sorted(a)
med1 = n[len(n) / 2]
med2 = n[(len(n)-1)/ 2]
print n
if len(n) % 2 == 0:
med = (med1 + med2) / 2.0
return med
else:
med = float(med1)
return med

print median([7,12,3,1,6])


#3

At first glance I notice that line 6 will return half the length of the list (if the list has 6 values (1, 2, 4, 7, 8, 1), it will return 3, rather than the value at 3, which would be 7 (count starts from 0).


#4
def median(numbers):
    list_sorted=sorted(numbers)
    if len(list_sorted)%2==0:
        med=(list_sorted[(len(list_sorted)/2)-1]+list_sorted[len(list_sorted)/2])/2.0
        
    else:
        med=list_sorted[int(len(list_sorted)/2)]
    
    return med
    
median([4,5,5,4])

worked for me and is bit shorter.


#5

n = raw_input("input a list: ")
def median(n):
m = sorted(n)
m1 = m[len(m)/2]
m2 = m[(len(m)-1)/2]
if len(m)%2 !=0:
return float(m1)
else:
return float(m1+m2)/2


#6

But if numbers was odd, then wouldn't len(list_sorted)/2 be a float, and how does list_sorted[float] know which index to take?

I know you put int, but in my code I didn't use int and for len(lists) = 3, lists[n/2] returns lists[2] and not lists[1.5].

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

print median([1, 2, 4])

#7

Seems like a good question... I can't work out why/how it picks the middle value. In my code below, if we take a list of 7 values as an example, the median result would be 3.5... so how does python know which value either side of that to display?

In a list of 7 values (lets say 10, 22, 33, 44, 55, 66, 77), the median is 44. The index of that value is 3... I don't know how a value of 3.5 gets us there... My code works - but can someone explain please?

def median(lst):
lst = sorted(lst)
med1 = lst[len(lst)/2]
med2 = lst[(len(lst)-1)/2]

if len(lst) % 2 == 0:
    med = (med1 + med2) / 2.0
    return float(med)
else:
    med = float(med1)
    return med