Median


#1



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


"Oops, try again. median([1]) returned [1] instead of 1"


I expected that it would've returned it correctly.


def median(lst):
    lst = sorted([lst])
    if len(lst) % 2 == 0:
        middle_right = len(lst) / 2
        middle_left = lst[middle_right] - 1.0
        middle_even = (lst[middle_right] + middle_left) / 2.0
        return middle_even
    elif len(lst) % 2 != 0:
        middle_num = len(lst) / 2
        return lst[middle_num]


#2

Problem1.
lst = sorted([lst])
why you putting lst in square bracket??

Problem2.
middle_left = lst[middle_right] - 1.0

Two problems here, you're calculating index so why lst[middle_right]? why not just middle_right ?
Youre subtracting -1.0 ?
Remember list index are integers.

Problem3.
Check this line of program..
middle_even = (lst[middle_right] + middle_left) / 2.0

Problem4.
middle_num = len(lst) / 2


#3

Thank you, but now I've tried to fix it but it still doesn't return the correct answer.

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

def median(lst):
    lst = sorted(lst)
    middle_num_position = 0
    middle_right_position = 0
    middle_left_position = 0
    if len(lst) % 2 == 0:
        middle_right_postion = len(lst) / 2
        middle_right = lst[middle_right_position]
        middle_left_position = (len(lst) / 2) - 1
        middle_left = lst[middle_left_position]
        middle_even = (middle_right + middle_left) / 2.0
        return middle_even
    elif len(lst) % 2 != 0:
        middle_num_postion = len(lst) / 2
        middle_num = lst[middle_num_position]
        return middle_num

#4

Nevermind, it was just a spelling error. It worked now. Thank you again!


#5

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