15. Median


#1

I have no idea were to start on this function,could someone please explain it. All that I have figured out are defining a new list and using a if/else to differentiate between a list with even amount of numbers and one with an odd amount...

def median(list):
    new_list = []
    sorted(list)
    if (len(list) % 2) == 0:
    
    else:

#2

In a list containing an odd number of elements, the median is the middle element of the sorted list.

[98,35,67,28,14]  =>  [14, 28, 35, 67, 98]
                                ^
                             median

In list containing an even number of elements, the median is the average (mean) of the middle two terms of the sorted list.

[4,5,5,4]  =>  [4, 4, 5, 5]

The median is float((4+5)/2) => 4.5

Follow this basic principle and you should be able to complete this problem. Ping us with your new code if you still have problems.


#4

So i figured out how to get the even one but for some reason am having trouble finding the median when the list has an odd amount of numbers...
def median(list):

def median(list):
    new_list = []
    sorted(list)
    list_length = len(list)
    #Even list 
    if (len(list) % 2) == 0:
        x = (list_length / 2) 
        y = (list_length / 2) + 1
        even_list = float(x + y) / 2
        new_list.append(even_list)
    #Odd List
    else:
        odd_list = 
        new_list.append(odd_list)
    return new_list

#5

This function returns a copy of the list, sorted, while leaving the original unmutated. It needs to be assigned to a variable. See the example in this post for a cases where we sort the list in place on the assumption that it is a literal list being passed to the function. [4,5,5,4] is a literal.

Study the example for clues. If your code looks complicated, it probably is doing too much. Think through the logic to find ways to simplify your steps and reduce code bloat.


#6

Sorry I still dont understand it I already sorted the list before my if/else statment was defined...


#7

But it needs to be assigned. sorted() does not copy back onto itself the way .sort() does.

s = sorted(list)