Click here to Skip to main content
15,921,548 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my code so far:

# x is the users input sorted, use x as parameter
# a is the index of the middle number in the odd version of x
# b is the 1st of the indexs in the even version of x
# d is the result of the 2 middle numbers
# being added together in the even version of x

def median(lst):

    x = sorted(lst)

    if len(x) % 2 != 0:
        # If the users input is odd
        a = len(x) // 2
        return(x[a])

    elif len(x) % 2 == 0:
        # If the users input is even
        b = len(x) // 2 - 1
        c = len(x) // 2
        d = (x[b] + x[c])
        ev_median = (d / 2)
        return(float(ev_median))

print(median([4, 5, 4, 5]))


Can you guys please explain to me what I should do differently? Thanks.

What I have tried:

Using a variety of different indexs, using regular division instead of floor-division.
Posted
Updated 4-Nov-22 11:41am

1 solution

Read the definition of median:
If the data set has an even number of observations, there is no distinct middle value and the median is usually defined to be the arithmetic mean of the two middle values

Your code doesn't do that: it takes two values which are outside the dataset, and averages them to get a result. Indexes are zero based, so valid indexes for a collection of four items are 0, 1, 2, and 3 only - the length of the collection - 4 - is not a valid index.
 
Share this answer
 
Comments
Naveen Krishna1 5-Nov-22 17:10pm    
Thanks. I also plugged the code into pycharm and it actually worked on their, I guess it could be an error with codecademy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900