Median


#1

Hi, can i find out what is wrong with my code? the console keeps telling me invalid syntax for else:

this is my code:
def median(listing):
listing=sorted([listing])
length=len(listing)
if length==1:
return listing[0]
elif length%2==0:
return (listing[(length-2)/2]+listing[(length-1)/2]
else:
return listing[(length-1/2)]


#2

It looks to me like you need to fix your function's use of 'RETURN':

  1. Either assign 'MEDIAN' a value just above the first 'IF' statement (right now your 'MEDIANS' seem to have the wrong scope) or -->

  2. Include 'RETURN MEDIAN' as the last step in each 'IF'/'ELIF'/'ELSE' statement, and remove the 'RETURN MEDIAN' statement you currently have at the end of your code.

ALSO:

  • Your 'ELIF' expression still needs a closing parenthesis, or a ')'.
  • Change the 'length%2 == 0' to have a '!=' comparator instead, as the expression you next use refers to a list of ODD length.

#3

thanks! now i tried this and this was the error that occured


#4

def median(lists):
lists=sorted(lists)
count=len(lists)

if count==1:
    return lists[0]
elif count%2==0:
    return (lists[count/2-1]+lists[count/2])/2.0
else:
   return lists[(count-1)/2]

TRY THIS... its works properly