Median 15/15

#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

Hi, I am tryng to do the Median exercise, but it always gives me a error and I cant understand why. I even added a bunch of code/prints to help me debug it but I really dont understand what is happening. If anyone could tell me what is happening I would be grateful. Thanks in advance

<Below this line, add a link to the EXACT exercise that you are stuck at.>

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median?action=lesson_resume

<In what way does your code behave incorrectly? Include ALL error messages.>

“median([4, 5, 5, 4]) resulted in an error: list index out of range”

<What do you expect to happen instead?>

To run without errors

``````def median(lst):
print "original list " + str(lst)
sort = sorted(lst)
print "Sorted list " + str(sort)
med = len(lst)
print "half of the list " + str(med)
if med % 2 == 0:
print "even"
a = sort[med]
print "A =" + str(a)
b = sort[med-1]
print "B = " + str(b)
print (a+b)/ 2.0
return (a+b)/ 2.0
else:
print "odd"
if len(lst) > 1 :
print "bigger than 1"
print "Median is " + str(sort[med/2])
return sort[med/2]
else:
print "equal to 0"
print sort[0]
return sort[0]

median([1,4,3,6,9,3,5])
``````

#2

lets say we have the following list:

``````[4, 5, 5, 4]
``````

then the length (a variable you named `med`) is 4, and the indexes are: 0, 1, 2, and 3. Agree?

look at this line:

``````a = sort[med]
``````

`med` is 4 (the length) and we just determined that the highest index is 3, so this will give an index error

#3

Thanks, now it runs! I had to make a few adjustments to the rest of the code, but it was so easy!

#4

A post was split to a new topic: Median

#5