Median


#1

Does anyone know whats wrong with my code? Thanks

def median(numbers):
    numbers = numbers.sort()
    median = 0    
    if len(numbers) == 1:
        median = numbers[0]      
    elif len(numbers) % 2 == 0:
        High_Half = numbers[len(numbers)/2]
        Low_Half = numbers[High_Half - 1]
        median = (High_Half + Low_Half) / 2
    else:
        Smaller_List = len(numbers) - 1
        median = numbers[Smaller_List / 2]

        return median

Median
#2

yep, and if you had taken the time to read answers in the topic (for example this one), you would know as well

Maybe a bit rude, but it is just that your respond to a topic, which had the exact same problem, and a solution to this problem was provided....


#3

I tried to take inspiration from your but I can't quite understand why mines doesn't work (sorry for any inconvenience)


#5

Okay, but what is it you didn't understand about my answer?

The problem is in this line:

median = (High_Half + Low_Half) / 2

lets say we have the following list: [4,5,5,4], after sorting and the rest we end up with High_Half which 5, and Low_Half which is 4, agree? (you can always add print statements to see what the code is doing)

so: 5 + 4 / 2 = 4. A integer (non decimal number) divided by integer will return a integer (if the outcome is a decimal number, the number gets floored). There are two easy ways to overcome the problem, divide by a float (decimal number) rather then a integer, or use float() to cast the whole thing to a float


#7

Ignore my last reply; "list index out of range" Bug is now I fixed; however, now I get "Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5" from this code (I'm pretty sure I used a float?);

def median(numbers):
numbers.sort()

if len(numbers) >= 1:
    median = numbers[0]

elif len(numbers) % 2 == 0:
    High_Half = numbers[(len(numbers))/2]
    print High_Half
    Low_Half = numbers[High_Half - 1]
    print Low_Half
    median = float((High_Half + Low_Half) / 2)

else:
    Smaller_List = (len(numbers) - 1)
    median = numbers[Smaller_List / 2]

return median

I'm probably wrong... bu i think my code is calculating high and low as indexes rather than numerical values?


#8

well, you have a bigger problem first, lets say you have the list: [4,5,5,4], which conditions you think is going to run? Wrong, it is your if, since 4 is great or equal then 1.

You might want to change this