python-3.xlistfunctionarithmetic-expressionsfloor-division

Floor divison operator applied to a list in Python


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.


Solution

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