# Median function return syntaxerror

#1

median

for some reason my line 9 return command keeps saying syntax error..

shouldnt the return command close the function and then its done?

``````Replace this line with your code.
def median(lists):
list_sorted = sorted(lists)
median = 0
if len(list_sorted) % 2 == 0:
median = (list_sorted(len(list_sorted)/2.0) + (list_sorted(len(list_sorted)/2.0)-1))/2.0
return (median)
elif len(list_sorted) % 2 != 0:
median = (list_sorted(len(list_sorted)/2.0)
return (median)``````

#2

i think you missed a " ) " on line 8 (after median =.....)

#3

but still get another error :v

#4

Here is my code. Hope it's helpful.

#5

I got to the same conclusion after looking around at another forum.. so i decided to change most of my code to have less brackets.. its working fine now

#6

That looks so kuch simpler than the one i made.. if you dont mind me asking whats the first if line for?

#7

I assume that we have only one item in the list x. Example x = [3] --> len(x) = 1

#8

You can still clean it by removing the First check and instead of 'int' you could use 'floor division' i.e. '// ' instead of '/'.
like this

``````def median(num):
x = sorted(num)
if not len(x) % 2:
return (x[len(x) / 2] + x[len(x) / 2 - 1] ) / 2.0
else:
return x[len(x) // 2]``````

#9

hey bud use this simple code and understand it:

``````def median(x):

s = sorted(x)
l = len(s)
m = 0
if l == 1:
return s[0]
else:
if l % 2 != 0:
a = l/2
a = int(a)
return s[a]
elif l % 2 == 0:
a = l/2
m = s[a] + s[a-1]
m = float(m)/2
return m``````

#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.