Median


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#


Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


When I run the same code on my machine it works just fine


def median(data):
    sorted(data)
    newData = remove_duplicates(data)
    if len(newData) % 2 > 0:
       return newData[int((len(newData)/2) - 0.5)]
    else:
        middle = int(len(newData)/2)
        return (newData[middle] + newData[middle - 1]) / 2
def remove_duplicates(newList):
    answer = []
    for item  in newList:
        found = False
        if(len(answer) > 0):
            for answerItem in answer:
                if answerItem is item:
                    found = True
                    break
        if found is False:
            answer.append(item)
    return answer


#2

the problem is that a integer divide by a integer gives an integer as result, so 5 + 4 (whchi is 9) divide by two is 4.

Too overcome this problem use float() or divide by a float since dividing by 2 is the same as dividing by 2.0


#3

Hey can you help me with this. This is how am calculating the median

def median(numbers):
    final = sorted(numbers)
    n = len(final)
    print(final)
    if n%2 != 0:
        return(final[int(n/2)])
    else:
        s = int(n/2)
        result = final[s-1]+ final[s]
        return(result/2)

error am getting is this - Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5.
I am not sure what am missing here.


#4

the problem is here:

return(result/2)

a integer (result, 9) divided by a integer (2) gives a integer as result (the number gets floored), try dividing by a float or use .float()


#5

This was my code:
def median(lst):
lst = sorted(lst)
if len(lst) % 2 == 0:
return (lst[len(lst) / 2] + lst[len(lst) / 2 - 1]) / 2.0
else:
return lst[len(lst) / 2]

I did get it right, but I don't understand the last line. The else is supposed to be for the odd number lists, so when you call len(lst) it should bring up an odd number. Once you divide that number by two it'll end up with a .5 on the end, so the index would be a .5 which isn't possible. Can someone explain why it's /2 instead of /2+.5?


#6

on this line:

return (lst[len(lst) / 2] + lst[len(lst) / 2 - 1]) / 2.0

you use 2.0 for the very reason that otherwise you get a integer (dividing integers gives a integer as result), which is why this works:

return lst[len(lst) / 2]

lets say len is 5, 5 / 2 = 2. because you divide two integers, the number gets floored.


#7

Thank you so much!!!