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):
    if len(anne)%2 == 0:
        for i in range(len(anne)):
            a = len(anne) / 2
            b = len(anne)/2+1
        for i in range(len(anne)):
    return median


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


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


can i see an updated version of your code?


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


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


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)
        m_ = int(m_)
        return lis[m_]


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