Median Problem in 'Practice Makes Perfect'


#1

https://gist.github.com/54fc7484f755c436522bf862eba4811a

Above is my code for the median exercise for the practice makes perfect lesson. The program is trying to run the list [4,5,5,4] but I'm receiving an error that my list index is out of range. does my problem perhaps have to do with a misuse of pythons starting index being 0? I feel like that might be it but I'm not sure. Any and all help is appreciated. Thank You!


#2

not sure how this calculate the median, but if you look at the value of j:

def median(leest):
    new_list=sorted(leest)
    first_half=[]
    j=1
    
    if len(new_list)%2!=0: #Meaning an odd number of numbers
        return new_list[len(new_list)/2]
    elif len(new_list)%2 ==0:#Meaning an even number of numbers
        while j<=(len(new_list)/2):
            for i in new_list:
                first_half.append(i)
                j+=1
    print j
    return (first_half[j]+new_list[j+1])/2.0

print median([4,5,5,4])

you can see j is 5, 5 is already an indexerror, let alone j+1 (6)


#3

This is how my code stands as of now....

""


""

I'm thinking that this may have to do with my nested while loop......


#4

i wouldn't use the loop at all, you should just calculate the middle index(es) based on the list length.

Go and write several list length and middle indexes on paper, see if you can find a pattern.


#5

""


""
I figured it out! Thank you stetim94.


#6