Median


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096

def median(unsorted_list):
    sorted_list = sorted(unsorted_list)
    if len(sorted_list) % 2 != 0:
        index = int(len(sorted_list) / 2) 
        median = sorted_list[index]
        print median
    if len(sorted_list) % 2 == 0:
        index_1 = int(len(sorted_list) / 2) 
        index_2 = index_1 -1 
        subtotal = (sorted_list[index_1] + sorted_list[index_2])
        median = subtotal / 2
        print subtotal, median, 9/2 # I used this line to see what was going on with my code, and it resulted that 9 / 2 = 4 instead of 4.5 Why is that happening?
    return median
    
print median([4,5,5,4])

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


#2

here:

median = subtotal / 2

dividing an integer by an integer results in a integer, if needs be the number is floored


#3

Because as @stetim94 mentions above, Python 2 returns an integer in integer division. We are required to declare a float when the case arises.

float(4 + 5) / 2  == 4.5

#4

Ouh, i forgot that rule, thank you, stetim94
Now it works perfectly


#5

Thank you, mtf, as well


#6