Median


#1

Can somebody please explain this code for me? I do not understand what it returns....

def median(lst):
s = sorted(lst)
l = len(lst)/2
if len(lst)%2 == 0:
return (s[l] + s[l-1])/2.0
else:
return s[l]



Replace this line with your code.


#2

def median(lst):
	s = sorted(lst) #sorts list in order of magnitude
	l = len(lst)/2 # finds mid value in the list by spliting the by two
	if len(lst)%2 == 0:
		return (s[l] + s[l-1])/2.0 # for two mid values, this would add them both and divide by 2.0 
	else:
		return s[l] #where above fails, returns the initial situation of just a single mid value 
print median([1,5,3,4])
print median([1,5,3])

Output

3.5
3

Hope this helps! :slight_smile:


#3

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