15/15 Don't understand the error message


#1

def median(numbers_list):
x = len(numbers_list)
numbers_list.sort()

if x % 2 == 0:
    m1 = x/2
    m2 = x/2 + 1
    median = (numbers_list[m1] + numbers_list[m2])/2

else:
    m = (x + 1)/2
    m = m - 1
    median = numbers_list[m]

return median

That's the error message I am getting: Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5
Should the median of 4,5,5,4 not be 5 anyway??


#2

How to compute median:

1) Sort the values:
4, 4, 5, 5
2) Pick the middle value
There isn't one because there are an even amount of values
3) If 2) not possible, take the average of the two middle values
(4 + 5) / 2 = 4.5

Length of that list is 4, the indexes you should average at are 1 and 2, which indexes do you use?

4.5 is also not an integer, so you can't use integer division to arrive at that result, you'll need to convert the sum to float before dividing it.


#3

I am using the halfpoint of the list which I get like so len(list)/2. Then I take that and add it to the index +1 from the list half point and divide that by two.

Now the error messages I keep getting confuse me because I get the right result. The median of 4,5,5,4 IS 5 so why does it tell me it should be 4.5? Same with 6, 8, 12, 2, 23 returns 7.0 instead of 8. The median of those numbers IS supposed to be 7.0 and not 8. So I don't understand where the problem lies. Is it just a wrong error message or is something entirely different wrong with my code?


#4

Sorry I am actually taking the halfpoint of the list and then the index -1


#5

Finally a solution! My problem was that I used the wrong sort function. n.sort modified the old list while sorted(n) helped me create a new list. I am also using the index now instead of subtracting 1 from the halfpoint of the list. It works fine now - here's the code:

def median(n):
num = sorted(n)
length = len(num)
x = len(num) / 2
index = length - 1

if length % 2 == 0:
    return (num[length/2] + num[index/2]) / 2.0

else:
    return num[x]

#6

I received the same error message with the code:

def median(mylist):
    sorts = sorted(mylist)
    length = len(sorts)
    if not length % 2:
        return (sorts[length / 2] + sorts[length / 2 - 1]) / 2
    return sorts [length/ 2]

I then looked on stacks overflow and saw that the recommended to change divisor from an int to a float so:

def median(mylist):
    sorts = sorted(mylist)
    length = len(sorts)
    if not length % 2:
        return (sorts[length / 2] + sorts[length / 2 - 1]) / 2.0
    return sorts [length/ 2]

The only difference between the code is that the second last line is divided by 2.0 instead of 2.

? --> can anyone explain to me why this produced a different result? As far as I understand math it shouldn't make a difference


#7

As far as I understood it you need to divide by 2.0 to get a float number in return. Otherwise your median would not be able to be displayed correctly if it happens to be 3.5 for example.