Median!


#1


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

I don't understand why this gives me the error "median([1]) resulted in an error: list index out of range"

Thanks a lot in advance!


def median(anne):
    anne=sorted(anne)
    if len(anne)%2 == 0:
        for i in range(len(anne)):
            a = len(anne) / 2
            b = len(anne)/2+1
            median=(anne[a]+anne[b])/2.0
        
    else:
        for i in range(len(anne)):
            a=(len(anne)-1)/2+1
            median=anne[a]
            
    return median


#2

why do you have loops? You can simply calculate the middle value(s) based on length without loop?


#3

Yes! It makes sense.
I corrected it but it still gives me the same error message. What else seems to be wrong?


#4

can i see an updated version of your code?


#5

I made some changes on the algorithm after reading the side-notes again and it worked now!
Thank you very much for help!


#6

that is actually more impressive, to fix it yourself. Be proud of yourself :smiley:


#7

Thoughts on this approach? I started out rough and had to troubleshoot back to this point. The lesson approved it but I would like your feedback on its effectiveness. Thanks!

def median(lis):
    lis = sorted(lis)
    l = len(lis)  #for simplicity along the way
    m = l/2.0
    mint = m-1.0
    m_ = m-0.5
    if l%2 == 0:
        mint = int(mint)
        m = int(m)
        return ((lis[mint]+lis[m])/2.0)
    else:
        m_ = int(m_)
        return lis[m_]

#9

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