About median function... 15/15


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
My function for computing median does not work when I input [1,2,3,4]. It keeps returning 2

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>
2.5 not 2 must be returned because it is mean of 2 and 3.

```python

def median(lst):
lst = sorted(lst)
if len(lst) % 2 != 0: # When list elements are odd
index_odd = len(lst)//2
return lst[index_odd]
else: # When list elements are even
index_even1 = len(lst)/2 - 1
index_even2 = len(lst)/2
mean = (lst[index_even1]+lst[index_even2])/2
return mean

print median([1,2,3,4,5])
print median([1,2,3,4])

<do not remove the three backticks above>

#2

the problem is here:

mean = (lst[index_even1]+lst[index_even2])/2

this results in:

(2 + 3) / 2

the problem is that if the division involves two integers, the resulted will be rounded down to the nearest integer

to get a float as result, the division should involve a float


#3

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