15 Median



This is the error I receive:
Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5

It seems like my code is returning the answer as an integer so it's being rounded up to 5 instead of returning the correct 4.5

How can I make sure that the answer returns as a float

Replace this line with your code. 
def median(numbers):
    for i in numbers:
        if len(numbers) == 1:
            return numbers[0]
        if len(numbers)%2 != 0:
            odd = numbers[len(numbers)/2]/2
            return odd
        if len(numbers)%2 == 0:
            even = (numbers[len(numbers)/2] + numbers[(len(numbers)/2 +1)])/2
            return even


Currently your program is returning 5 regardless of using floats or ints. If you work through your even if statement, to get the first number it looks at the length, in this case 4, and divides it by 2, which equals 2. Then it does the same thing and adds 1 to it. That means that it is pulling elements 2 and 3 which are the 3rd and 4th because it starts at 0. Now that is an easy problem to fix.

To make it use floats when you divide by 2 to get the average use float(2).


@terawhiz95466 If you divide by a float Python will return a float. For example 14/2.0 will return 7.0

Also, you may want to remove your for loop. In this instance it isn't really doing anything since you are not iterating over the items in the list. It will actually slow your program down because, as I understand for loops, you will be running your conditional statements the number of times that is equivalents to the length of the list, when you really only need to be running it once.

Here is the code that worked for me - hope it helps!

def median(lst):
    if len(lst) % 2 == 0:
        med = (len(lst)/ 2)
        return (lst[med] + lst[med - 1])/2.0
        med = (len(lst)/2)
        return lst[med]


This is what I ended up doing and was really proud of!

def median(list):
    list = sorted(list)
    if len(list)%2==0:
        return (list[(round(len(list)/2))] + list[(int(len(list)/2)-1)])/2
        return  list[int(len(list)/2)]


Congrats, man! That's some efficient code right there.


Nice! After I cleaned my code up mine was very similar.
I noticed you use 'round' and 'int', is there a reason for this?
Mine seems to work without them.

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


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.