15. Practice Makes Perfect Issues


#1



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


I can't seem to figure out why my code isn't working. Whenever I run it, it gives me the error message:


median([1, 34, 1, 6, 8, 0]) returned 7.0 instead of 3.5

This doesn't make sense to me since it works for things like [4, 5, 5, 4]. Any help would be greatly appreciated.


def median(lst):
    sort = sorted(lst)
    if len(sort)%2==0:
        return ((lst[(len(lst)/2)]+lst[((len(lst)/2)+1)])/2.0)
    else:
        return lst[((len(lst)/2)-1)]


#2

First rule of programming, write readable code and avoid duplication. We can start with the len() function which appears four times in the code.

def median(lst):
    temp = sorted(lst)
    t_len = len(temp)
    n = t_len / 2       # will be an integer
    if t_len % 2:       # lenth is odd
        return temp(n)
    else:
        return float(temp[n - 1] + temp[n]) / 2

#3

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