Median

#1

Oops, try again. median([6, 8, 12, 2, 23]) returned 7.0 instead of 8

Why 8? It should return 7.0 I am really confused!
P.S. It works fine in PyCharm, and function return is 7.0

``````def median(lst):
lst = sorted(lst)
index = int(len(lst) / 2)
len_sum = (lst[index] + lst[index - 1]) / 2.0
return len_sum

print(median([6, 8, 12, 2, 23]))``````

#2

The median there is 8. A visit to wikipedia perhaps, if you're really getting 7 manually.

#3

How we get 8? 7 is clear (12 + 2) / 2

#4

wiki. gogo.

#5

Thank you, now I understand that my mistake was in odd list numbers.

``````def median(lst):
lst = sorted(lst)
print(lst)
if len(lst) % 2 == 0:
index = int(len(lst) / 2)
len_sum = (lst[index] + lst[index - 1]) / 2.0
return len_sum
elif len(lst) % 2 == 1:
result = len(lst) / 2
result = int(result)
return lst[result]
print(median([6, 8, 12, 2, 23]))``````

#6

Not positive since I've only been learning Python since yesterday, but...

Median is when you order them from least to greatest and find the middle number.

Ex: 2, 6, 8, 12, 23
So 8 is the median.

What you explained was Range. Where you take the smallest and largest number, add them together and divide by 2.

#7

why we need write 2.0 rather than 2 in " len_sum = (lst[index] + lst[index - 1]) / 2.0"sentence?

#8

The 2.0 is to ensure a non-integer answer if it's needed.

(4 + 15) / 2 = 19 / 2 = 9

(4 + 15) / 2.0 = 19 / 2 = 8.5