-1
def median(numbers):
    numbers.sort() 
    if len(numbers) % 2:
        # if the list has an odd number of elements,
        # the median is the middle element
        middle_index = int(len(numbers)/2)
        return numbers[middle_index]
    else:
        # if the list has an even number of elements,
        # the median is the average of the middle two elements
        right_of_middle = len(numbers)//2 
        left_of_middle = right_of_middle - 1
        return (numbers[right_of_middle] + numbers[left_of_middle])/2

Examples of results:

>>> x=[5,10,15,20]
>>> median(x)
12.5
>>> x=[17,4,6,12]
>>> median(x)
9.0
>>> x=[13,6,8,14]
>>> median(x)
10.5

I have run this function and it works fine. At the beginning it was diffilcult to understand the results but finally I got it!.

However, I do not understand why only the first result is like it is intended to be. I mean the result is the average of the two middle numbers of the list.

I hope you understand I am learning on my own and sometimes it is not easy.

MarianD
  • 13,096
  • 12
  • 42
  • 54
doer76
  • 11
  • 6

3 Answers3

1

Your function works only in the first example because only the first list is sorted. Sort the other list or sort within the function.

Doncho Gunchev
  • 2,159
  • 15
  • 21
0

Simply because of that line:

numbers.sort() 

so, [17,4,6,12] becomes [4,6,12,17] which his median is 9

scharette
  • 9,437
  • 8
  • 33
  • 67
0

You are probably asking:

Why is the median different from the mean?

The answer is then this:

The median is the value separating the higher half of a data sample, a population, or a probability distribution, from the lower half.

(From Wikipedia.)

For a data set, the terms arithmetic mean, mathematical expectation, and sometimes average are used synonymously to refer to a central value of a discrete set of numbers: specifically, the sum of the values divided by the number of values.

(From Wikipedia.)

Those two values may be equal but in general there are different:

If you have 10 poor people and a 1 millionaire, the mean will be very high, but the median (the salary of the 6th most poor person) will be still very low.

MarianD
  • 13,096
  • 12
  • 42
  • 54