15/15 median


#1

Hello, I have this code here:

def median(num):
    items = sorted(num)
    length = len(num)
    med = 0
    med1 = 0
    med2 = 0
    if length % 2 == 0:
        med1 = int(length / 2.0)
        med2 = med1 + 1
        med = (items[med1] + items[med2]) / 2.0
    else:
        med1 = int(length / 2.0)
        med = items[med1]
        
    return med

When I run it, I get this error message: "Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5"
What's wrong with my code? I'm unsure of what I'm doing wrong.


#2

try

med2 = med1 - 1

#3

A) Rydan, your the man, man.
B) So I assume masterofwaffles wants med1 to be the lower median if the list of numbers is even. In that case you have to go back and make length = len(num) -1. Then med1 becomes (med1 = int(length/2.0)) correct as is. As you have it, waffles, the length is 1 greater than the actual list of indexes for the listed numbers. That is why Rydan is telling you to -1 in your med2. You have actually calculated the higher med or what I think you consider to be med2 in your variable med1.


#4

Hi,

Please try this. Its working fine...

def median(lst):
lst = sorted(lst)
length = len(lst)

if length % 2 == 0:
    mdn = (lst[(length - 2) / 2] + lst[(length) / 2]) / 2.0
else:
    mdn = lst[(length - 1) / 2]
return mdn

#5

Facedesk That was the exact same mistake I was making. Sort of on the right track, but I needed to change my +1 to a -1 for one of my spots.


#6

they have to fix this exercise. Whenever the generated by codeacademy list used as the argument for the function has an even length, the result is always the second number.

So you see, this code is accepted:

def median(lst):
size_lst = len(lst)
if size_lst % 2 == 0:
if lst == [4,5,5,4]:
return 4.5
n1 = lst[(size_lst // 2)-1]
n2 = lst[(size_lst//2)]
return (n1+n2)/2.0
else:
if size_lst == 1:
return lst[(size_lst//2)]


return lst[1]

Pretty ridiculous I would say

#7

this is what i got

def median(num):
    sort_num = sorted(num)
    print sort_num
    middle = len(sort_num)/2

ex: 7/2=3.5, as it is int, then middle = 3

ex: 8/2=4, as it is int, then middle = 4

    if (len(sort_num) %2 == 1):

ex: if length = 7 (odd), then element at "index[middle]" is median

        return sort_num[middle]

    else:

ex: if length = 8 (even), then element at "index[middle]" and "index[middle-1]" should take average

        return float(sort_num[middle]+sort_num[middle-1])/2.0 

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

#8
def median(list):
    list = sorted(list)
    amount = len(list)
    if amount % 2 == 0:
        median = amount / 2
        middle = list[median] - list[median - 1]
        middle = float(middle) / 2
        median = list[median - 1] + middle
        return median

    elif amount % 2 != 0:
        median = amount / 2
        return list[median]