Median


#1

def median(lst):
	total = 0
	sorted_list = sorted(lst)
	if len(sorted_list) % 2.0 == 0:
		right_middle = sorted_list[len(sorted_list) /
		2]
		left_middle = sorted_list[right_middle - 1]

		total += (right_middle + left_middle) / 2.0
		return total
	else:
		total += (len(sorted_list) * 0.5) + 0.5
		return total

I get this error on codeacademy:
Oops, try again. median([1]) returned 0 instead of 1

Also, when I call this list for example:

print median([1,3,4,6,5,7,8,9])

I get a result of 6.5 instead of 5.5 (in coderunner 2)
`


#2

here:

total += (len(sorted_list) * 0.5) + 0.5

why * 0.5) + 0.5?

look at this table;

1 / 2 = 0
3 / 2 = 1
5 / 2 = 2
7 / 2 = 3

for lists with odd number of items (left column) divided by 2 perfectly gives you the middle index (right column) you need


#3

def median(lst):
	total = 0
	sorted_list = sorted(lst)
	if len(sorted_list) % 2 == 0: 
		right_middle = sorted_list[len(sorted_list) /
		2]
		left_middle = right_middle - 1
		total += (right_middle + left_middle) / 2
		return total
	else:
		total += (len(sorted_list) / 2)
		return total

Returns the error: Oops, try again. median([1]) returned 0 instead of 1


#4

this:

len(sorted_list) / 2

will give you the index, you still need to access the list


#5

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