Help on median


#1

On the median exercise at:
https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#

My code returns :
Oops, try again.median([4, 5, 5, 4]) returned 5.0 instead of 4.5

def median(numbers):
    number_list = sorted(numbers)
    length = len(numbers)
    if length%2 == 0:
        median = numbers[(length/2) - 1] + numbers[length/2]
        median = median/2.0
    elif length ==1:
        median = numbers[0]
    else:
        median =numbers[length/2]
    return median

please help me figure out whats wrong


#2

What result would you get manually for that list? What does your code do differently from what you'd do manually? How can you observe what happens or test if it does what you expect for a particular operation? What could it possibly be doing to arrive at that result, and how can you confirm whether that is happening?


#3

Look at the list of numbers you are using to calculate the median. The median value is determined on a sorted list of numbers........


#4

Got it. I never got the sorted list in use in the first code , that's what was wrong.

New code works fine:

def median(numbers):
number_list = sorted(numbers)
length = len(numbers)
if length%2 == 0:
median = number_list[(length/2)] + number_list[(length/2) - 1]
median = median/2.0
elif length ==1:
median = number_list[0]
else:
median =number_list[length/2]
return median


#5

thanks for all the help


#6

This also helped me, I used the sorted function incorrectly!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.