What is wrong with my logic?


#1

Hi guys im in course python -> practice makes perfect-> median... i have a problem with my code can u guys tell me what is worng with my logic?!?

def median(lst):
    if len(lst)%2==0:
        l=len(lst)/2
        a=(lst[l]+ lst[l+1])/2
        return a
    else:
        l=len(lst)/2
        l += 1
        l=lst[l]
        return l
print median([1,1,2])

here is what i think should have happened! as the list is passed , in the if condition it is identified as not equal to 0 so switches to else part. There the i'm trying to finding the middle element here 3/2 =1 now l=1. in the next step
i'm adding +1 because of the list contains odd number of elements. Next i'm saving the value of lst[2] in l and returning it.. this should have printed 1 as answer nut it gives 2 as answer and error message "Oops, try again. median([1]) resulted in an error: list index out of range".. Thanks in advance guys.....


#2

i understand your logic, but it isn't right, lets say we parse your list ([1,1,2]) into the function, the length is 3 (say if some step doesn't make sense), so obviously it goes to the else part of your code. then this line:

l=len(lst)/2

len(lst) is obviously 3, divided by 2 is 1. (a integer divided by a integer is a integer, everything after the decimal get thrown away). But here is the thing, the first index of an array is 0. so your 3 items are indexed 0,1 and 2. So, 1 is already the middle, no need to add one, remove this line: (l += 1)

now, you can do the math, but if your list has one item: 1 / 2 = 0, which so happen to match the item(and explain the out of range error, since there is no item at index 1).
5/2 = 2, which is the middle item (indexes are 0,1,2,3,4), two is the middle one.

Now, there are more problems with your code, if you need more help, let me know. Here is one more tip: the exercise is going to try a few lists, so i would sort your list (at certain point they will throw the list 4,5,5,4 at your function, if you don't sort the list, you will never get the right median. And remember about what i said, a integer divided by a integer is a integer, you are going to need that. Good luck


#3

Thank you for explaining .... now i know where the problem is