Can't figure out my mistake, what's wrong here?


#1

MEDIAN


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

It gives the following message :Oops, try again. Your code did not run to end. Check the console window for errors!

I have to find the median. What should I do to make it correct, please help.


def median(numbers):
    new_list = sorted(numbers )

    for number in new_list:
        if len(new_list) % 2 != 0:
            position = (len(new_list) + 1) / 2
            medn = new_list[position]
        else:
            position1 = (len(new_list)/2)
            position2 = (len(new_list) + 2)/2
            medn = (new_list[position1] + new_list[position2])/2
    return medn


#2

Try making your if statement if len(new_list) % 2==0:


#4

I did, It wont work.
if len(new_list) % 2==0:
then it means sequence with an even number of elements.


#5

My code runs with it. However mine is a little different than yours. Take a look at this:

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

#6

Thank you, it worked.
But,I still cant figure out the error in my code.


#7

It probably got hung up on the for loop for some reason. Sorry I couldn't figure out the problem for you.


#8

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