Practice makes perfect 15. median


#1

hi im on this lesson and ive done my coding here it is

def median(lit):
  lit.sort() # sort the list 
  if len(lit) % 2 != 0: # if there are an odd number of items in list
    middle = len(lit)  / 2 # find the middle index, since index starts at 0 i divide 
  return lit[middle] # access the value within that index to get the median
  if len(lit) % 2 == 0: # if there are an even number of items in list
    mid1 = (len(lit) - 1) / 2 # find the lower middle index, since index starts at 0 i minus 1 and divide
    mid2 = (len(lit) + 2) / 2 # find the upper middle index, i add 1 and divide
  return (lit[mid1] + lit[mid2]) / 2  # access the values of those two indexes, add them and divide by 2 to get the median

the error i get is
median([4, 5, 5, 4]) resulted in an error: local variable ‘middle’ referenced before assignment

i wanted to know how to fix this error or if what im doing is not even close to the right thing.

one more question, to could u find a half index, such as the 2.5th piece instead of finding the value of the 2nd and 3rd and finding the mean of those?


#2

Hi @h2zero,

Your two return statements should be indented enough to make them part of the conditional blocks that precede them. As you have it now, the first one attempts to execute regardless of whether the list contains an even or odd number of items.

Sorry, but a list cannot be accessed via half indexes.


#3

thanks it worked after i indented the return statements, but im confused since pretty much every other time the return statement is always in line with the if or the for statements, what difference does where the return is indented make?


#4

Increasing the indentation of the two return statements makes them each part of an appropriate if block so that each one executes only when the appropriate condition is satisfied.

This statement should execute only when there are an odd number of items in the list

  return lit[middle]

Also note that the variable middle becomes defined in the assignment statement above it, which is …

    middle = len(lit)

If the return statement is outside the if block, it attempts to execute every time the median function is called, rather than only if there are an odd number of items in the list. In fact, when there are an even number of items in the list, middle is not defined, and attempting to execute the statement that uses it as an index raises an error.

For analogous reasons, this statement should also be included in a conditional block, so that it only executes if there are an even number of items in the list, which is also the condition under which mid1 and mid2 become defined …

  return (lit[mid1] + lit[mid2]) / 2

Note that attempting to execute that statement when mid1 and mid2 have not been defined would raise an error.


#5

alright thanks i understand better now, i guess thats why i was getting the error before. thanks alot


#6