Median


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

I'm getting the correct answer running my code on Spyder (Anaconda). Is this version problem?


Replace this line with your code.


#5

dividing two integers ( 9 /2 ) will give a integer as result, if needs be the result is floored. divide by a float (2.0) or use float() to cast something to a float


#6

I wanted to avoid posting but I give up. I can't figure out what's wrong with my code. I'm getting the error "Oops, try again. median([1]) resulted in an error: int() argument must be a string or a number, not 'list'". Any help is appreciated. Thanks!

def median(stuff):
number = sorted(stuff)
length = len(number)
if length%2 == 0:
return number([length/2] + number[length/2-1])/2.0
else:
return number[length/2]


#7

Make sure it's easy to reproduce what you describe. It should be possible to copy from your post, load the exercise, paste it in, hit run, get the same result. That's not the case here, so others will be unable to reproduce your issue.

After changing your indentation to the following:

def median(stuff):
    number = sorted(stuff)
    length = len(number)
    if length%2 == 0:
        return number([length/2] + number[length/2-1])/2.0
    else:
        return number[length/2]

It still does not produce the same result.


#8

my apologies. The indentation looked correct in the word editor. After reloading the page and entering and resetting the code, I did not get the same error. instead i get the error "Oops, try again. median([4, 5, 5, 4]) resulted in an error: can only concatenate list (not "int") to list". I have read through the other median threads to try and figure out what i'm doing wrong, but I'm at a loss.

Am I concatenating a list? I thought that

would be referencing the int within the list?


#9

You could call the function yourself to get the full error message

>>> median([4, 5, 5, 4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "median.py", line 5, in median
    return number([length/2] + number[length/2-1])/2.0
TypeError: can only concatenate list (not "int") to list

Given that it shows you the line, says that the left side is a list and the operation is concatenation (+) and that the right side is int, you have a lot of information right there from just cross-referencing your line and the error message.


#10

I just figured out my issue. I had the open parenthesis in the wrong position. Thank you for your assistance!


#11

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