15.Median (practice makes perfect)


#1




Hey guys. first post on this forum so go easy on me haha. Basically im stuck on this exercise and cant quite understand why its not working. Any help would be greatly appreciated

error message:
Oops, try again. median([1]) returned [1] instead of 1


def median(numbers):
    numbers=sorted([numbers])
    length=len(numbers)
    for num in numbers:
        if length==1:
            return numbers[0]
        elif length%2!=0:
            return length/2
        else:
            return (((length/2)-1)+(length/2))//2.


#2

Your error message says that your function returns a list, but the code you posted won't do that.
The code you did posted returns things like the first element or the length divided by two, that's not at all what the median is. Refer to how you would do it manually, your code should do the same thing. What is the purpose of the loop? Would you do that manually? Why does it need to be there?

(yeah you only return the first element when there's only one element in the list, but why should that be a special case?)

These mistakes have more to do with what actions are required to compute a median than with the language. Start by figuring out what needs doing.


#3

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