Median - Can't Figure Out What's Wrong


#1

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

<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

<In what way does your code behave incorrectly? Include ALL error messages.>
I’m getting this error message which indicates my else: is indented wrong.

File “python”, line 7
else:
^
IndentationError: unexpected indent

<What do you expect to happen instead?>
However, when I bring hit backspace to bring it to the left I get this error:

File “python”, line 7
else:
^
SyntaxError: invalid syntax

Tabbing to the right one indent from the original spot give the same initial error.

```

def median(nums):
sortedList = sorted(nums)
if len(sortedList) % 2 == 0:
mid = int(len(sortedList) / 2.0)
result = (sortedList[mid] + sortedList[mid - 1]) / 2.0
return result
else:
mid = int(len(sortedList) / 2.0 - 0.5)
result = sortedList[mid]
return result

<do not remove the three backticks above>

#2

Hi @skisma,

Check your indentation. I tested your code and it works fine for me with correct indentation.


#3

Check your code. Remember, it’s 2 spaces for each level of indentation.

def median(nums):
  sortedList = sorted(nums)
  if len(sortedList) % 2 == 0:
    mid = int(len(sortedList) / 2.0)
    result = (sortedList[mid] + sortedList[mid - 1]) / 2.0
    return result
  else:
    mid = int(len(sortedList) / 2.0 - 0.5)
    result = sortedList[mid]
    return result

and then you can check your function to see it works by using these number sets:

print median([2,3,1,4,5])
print median([4,2,3,1])
print median([10,5,25,15])

#4

Odd, I’ve tried it the way you have listed and also tried with the returns outside of the if/else and it’s still not working either way. Indents are 2 spaces or 1 tab which is what I’m doing.

def median(nums):
  sortedList = sorted(nums)
  if len(sortedList) % 2 == 0:
    mid = int(len(sortedList) / 2.0)
    result = (sortedList[mid] + sortedList[mid - 1]) / 2.0
return result
  else:
    mid = int(len(sortedList) / 2.0 - 0.5)
  	result = sortedList[mid]
return result

This code above returns this error:
File “python”, line 7
else:
^
IndentationError: unexpected indent


#5

Try 4-space indentation. I think that’s the default indention the interpreter wants.

Look at your if/elif statement:

Anything under your if/else statement/s should have the same indentation level, or else, you’ll get errors.


Indentation example:

def myfunct(a): 
     if this and that:  #we indent our code under our function.
        #what we want to execute if true will happen here.
     else:
       #other than that, this will execute.

Think of it like this, if you see a :, either after a statement, function, loop, or something that you’ll soon learn, that means you should indent your code below it because that tells python that the block indented after the : is what will execute. If you don’t indent your code below that, Python will tell you it expected something to be indented below it because it saw :.

Studying the error codes given helps a lot. :slight_smile:


#6

I don’t want to say it bad man just copy paste the code of hellofromtonya again I did it and it worked I tried so many ways. In your third reply put the (else:) in the same position with (if :). I hope to find solution


#7

Look at your code vs. the code that I shared with you. The indentation is not correct in yours:

def median(nums):
  sortedList = sorted(nums)
  if len(sortedList) % 2 == 0:
    mid = int(len(sortedList) / 2.0)
    result = (sortedList[mid] + sortedList[mid - 1]) / 2.0
return result # This needs to be indented 4 spaces
  else:
    mid = int(len(sortedList) / 2.0 - 0.5) # This needs to be indented 2 more spaces
  	result = sortedList[mid] # This is indented too far.
return result # This needs to be indented 4 spaces

#8

Sorry for the confusion, the code you’re showing here is only one of the things I tried. I didn’t include the version with the indented returns like you had since you had already provided it above, but I did try that too. I think this might warrant a bug report because I just tried again with the properly indented returns and it didn’t work. Then I pasted in your block from above (thanks @orestisio) which was identical to what I had, and it ran just fine. I made sure to watch closely and edit undo/redo several times to be positive and it’s the same code. Here’s some screenshots:

My Code:

Tonya’s Code:


#9

Go ahead and submit a bug report. Include the details to give context to the problem. Like you, I found the interface a bit buggy with the IndentationError. It took manually resetting each line, refreshing the browser, and a few words or two at the screen.


#10

Code Tips

I’d like to give you a challenge to refactor your code and remove the redundancy, i.e. if you’re up for it.

Eliminate Redundancy

Notice that you are getting the length of the sortedList more than once. A good rule of thumb is to write code one time. Therefore, you could store that into a variable and then use the variable represent the actual number of items in that list:

def median(nums):
    sortedList = sorted(nums)
    numItems = len(sortedList)
    if numItems % 2 == 0:
       #the rest of your code

Next, notice that you are computing the middle number twice. That’s another opportunity to refactor.

Just Return

Another strategy is to just return instead of assigning a result into a variable and then returning that variable. It’s one less line of code for each instance, which in your code is x2.

Give it a try.


#11

Of course I’m up for it, it means more learning.

Okay so I understand your first and last points, but not your 2nd regarding computing the middle twice. Don’t I need to twice for the two different scenarios the length of sortedList can be (even and odd)?

Here’s what I have now:

def median(nums):
  sortedList = sorted(nums)
  numItems = len(sortedList)
  if numItems % 2 == 0:
    mid = numItems / 2.0
    sortedList[mid] + sortedList[mid - 1] / 2.0
    return
  else:
    mid = numItems / 2.0 - 0.5
    sortedList[mid]
    return

#12

Excellent! I had a feeling you dig diving into some code quality.

Exploring the problems first.

    sortedList[mid] + sortedList[mid - 1] / 2.0
    return

Hold on. You’re not returning anything from the function. Why? You have the work on the line above it. You want to return that. Right?

Same thing here:

    sortedList[mid]
    return

Problem #2

sortedList[mid] + sortedList[mid - 1] / 2.0

Think about the Order of Operations in Math. Division takes precedence over addition. Right? For example:

print 4 + 2 / 2 # //-> 5 because 2/2 = 1 + 4 = 5
print (4 + 2) / 2 # //-> 3 because 4 + 2 = 6 / 2 = 3

Problem #3

Why are you subtracting 0.5 to get the middle index when the list has an odd number of items? Go back to the instructions. For example for a list of [1, 3, 6, 7, 12], the median is 6. It’s the middle index of the list.

Finding the median of [7, 12, 3, 1, 6] would first consist of sorting the sequence into [1, 3, 6, 7, 12] and then locating the middle value, which would be 6.

Think about that one.

Reusing a middle index

Median in all cases starts with grabbing the middle index, i.e. middleIndex = numItems / 2. You then reuse that middleIndex in 3 different places. Give it a try.

Go ahead and give it a try. I’m here to help.


#13

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