[SOLVED] Median (list index out of range)

#1

I need two more eyes on this.
Below you can find my code for the exercise. It gives me "list index out of range" for the case with list [4, 5, 5, 4]. Question is, I tried the code apart and it works, even for different lists:

``````sequence = [4, 5, 5, 4]
sort = sorted(sequence)
print sort
lf = sort[:len(sort)/2]
rg = sort[len(sort)/2:]
avg = float((lf[len(lf)-1]+rg[0]))/2
print lf[len(lf)-1]
print rg[0]
print avg``````

Here's the code I used for the function:

``````def median(sequence):
sort = sorted(sequence)
if len(sort) % 2 == 0:
lf = sort[:len(sort)/2]
rg = sort[len(sort)/2:]
avg = float((lf[len(lf)-1]+rg[0]))/2
return avg
else:
indmed = len(sort)/2
return sort[indmed]``````

Thank you in advance for any help!

#2

``````def median(sequence):
sort = sorted(sequence)
if len(sort) % 2 == 0:
lf = sort[:len(sort)/2]
rg = sort[len(sort)/2:]
avg = float((lf[len(lf)-1]+rg[0]))/2
return avg
else:
indmed = len(sort)/2
return sort[indmed]
print median([4,5,5,4])``````

(i just added a function call), and it worked fine:

And it worked fine, maybe your browser is sending cached data after a few attempts? Try a different browser

#3

I cleaned the cache and it worked. Thanks for the suggestion!