# 15/15 median: list not sorting?

#1

Hi all,

Wondering why this code isn’t working. It’s probably a really silly and obvious mistake, so please be gentle with me:

import math

def median(mylst):
l = sorted(mylst)
# if the list has an even number of elements
if len(l) % 2 == 0:
first_mid = l[int(math.floor(len(l)/2))]
last_mid = l[int(math.ceil(len(l)/2))]
mid_avg = (first_mid + last_mid) / 2.0
return mid_avg
# if the list has odd num elements
else:
return l[int(math.ceil(len(l)/2))]

I get the error: median([4, 5, 5, 4]) returned 5.0 instead of 4.5

#2

both first_mid and last_mid have a value of 5:

import math

def median(mylst):
l = sorted(mylst)
# if the list has an even number of elements
if len(l) % 2 == 0:
first_mid = l[int(math.floor(len(l)/2))]
last_mid = l[int(math.ceil(len(l)/2))]
print first_mid, last_mid
mid_avg = (first_mid + last_mid) / 2.0
return mid_avg
# if the list has odd num elements
else:
return l[int(math.ceil(len(l)/2))]
median([4, 5, 5, 4])

as you can see here. I added some print statements so we can see

that can’t be right, how come both values are 5? What do you think? You can add a print statement to see if the sorting goes right? See where things go wrong

little spoiler if you are ready:

the sorting is fine

#3

Woooow. I just saw my error. It was a silly mistake. It has to do with the values of the positions assigned to lists… facepalm

Thanks for the help The code works now!

#4

the indexes you attempted with math ceil and math floor where no good

good to hear you found your mistake

#5

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