15.median


#1

def median(lists):
sorted_list = sorted(lists)
if len(sorted_list) == 1:
return sorted_list[0]
elif len(sorted_list) % 2 == 0:
first = len(sorted_list) / 2
second = first - 1
total = (sorted_list[first] + sorted_list[second])/2
return total
else:
first = (len(sorted_list)+1)/2
total = sorted_list[first]
return total

it giving error like "Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5"


Median (15)
#2

Hi,

Keep in mind that when dealing with int values you need to explicitly tell python that you want float(decimal) values in the result, otherwise it will convert (round) it to int.

Try doing so by dividing with "/2.0" and not "/2"
Also there some index calculation issues, here is your corrected code:

def median(lists):
	sorted_list = sorted(lists)
	if len(sorted_list) == 1:
		return sorted_list[0]
	elif len(sorted_list) % 2 == 0:
		first = len(sorted_list) / 2 - 1
		second = first + 1
		total = (sorted_list[first] + sorted_list[second])/2.0
		return total
	else:
		first = len(sorted_list)/2
		total = sorted_list[first]
		return total

Just in case here is some some extra code as an alternative solution:

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

#3

thank you :grinning:


#4

I get the error:
Oops, try again.
median([4, 5, 5, 4]) resulted in an error: unsupported operand type(s) for /: 'list' and 'float'
What does it mean?

def median(lista):
sorted_list = sorted(lista)
if len(sorted_list) == 1:
return sorted_list[0]
elif len(sorted_list) % 2 == 0:
first = len(sorted_list/2.0 - 1)
second = len(first+1)
total = (sorted_list[first] + sorted_list[second])/2.0
return total
else:
first = len(sorted_list)/2.0
total = sorted_list[first]
return total


#5

Hi,
By doing so:

You get decimal index of an array when it can be only int.
Try dividing simply by /2 and python should round it down automaticaly

first = len(sorted_list)/2


#6

Yes! I seem to get it to work now! Thank you!


#7

I feel like this solution is pretty much the same as yours, but I get the error median([4, 5, 5, 4]) returned 5.0 instead of 4.5. What did I do wrong?


#9

Hint:
Something is missing on line 2

Spoiler Solution

lst = sorted(lst)