# 15/15 Median

#1

Can’t figure why this isn’t working. Error message is “median([4, 5, 5, 4]) returned 5 instead of 4.5”. Can anyone throw me a hint or two?

``````
> def median(sequence):
>   result = 0
>   x = 0
>   med = 0
>   sequence.sort()
>
>   if len(sequence)  % 2 == 0:
>     x = len(sequence) / 2
>     result = sequence.pop(x)
>
>   elif len(sequence) % 2 == 1:
>     x = len(sequence) / 2
>     med = (len(sequence) / 2) + 1
>     if x > 0:
>       result = (x + med) / 2
>     else:
>       result = sequence.pop(0)
>
>
>   return result
``````

#2

you seem to have swapped the `if` and `elif` condition, your `if` statement is true for lists of even length, yet when you look at the code in the if clause, it looks like code which you would use for a list of uneven/odd length, same is true for `elif` (but then of course the other way around)

also, this line:

``````med = (len(sequence) / 2) + 1
``````

why `+ 1`?

also, a division which involves two integers, will give an integer as result

#3

Thanks, this helped me realize the problems with my code. I decided to try a different route to solving the problem and I found a much easier way. I’ll share it below

#4
``````def median(sequence):
result = 0
x = 0
sequence.sort()

if len(sequence)  % 2 == 0:
result = float(sequence[len(sequence) / 2 - 1] + sequence[len(sequence) / 2]) / 2

elif len(sequence) % 2 == 1:
x = len(sequence)
if x > 1:
result = float(sequence[(len(sequence) / 2)])
else:
result = sequence.pop(0)

return result)
``````

#5

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