Median: Help?


#1


I'm on the median part of the section.


When I do numbers like [1, 3, 5, 7], it'll work fine, but if I do numbers like [1, 2, 3, 4], it returns 2 instead of 2.5. Any help?


from math import floor

def median(n_s):
    nums = sorted(n_s)
    if len(nums) % 2 == 0:
        first = nums[len(nums)/2 - 1]
        second = nums[len(nums)/2]
        num = (first + second) / 2
    else:
        num = nums[int(floor(len(nums)/2))]
    return num

numbers = [1, 2, 3, 4]

print median(numbers).


#2

The above will return the floor value of integer division. Divide by a float to implicitly declare a float.

integer / 2.0  =>  float

Alternately, explicitly declaring a float,

float( a + b ) / 2  => float

Can be simplified. As mentioned above, integer division quotient is a floor value, already.

num = nums[len(nums) / 2]