Median


#1



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

Any Ideea why this won't work?


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


Replace this line with your code. 

def median(x):
    x = sorted(x)
    for i in range(len(x)):
        if len(x) % 2 == 1:
            x[i] == len(x) % 2
            return x[i]
        else:
            x[i] == (len(x) %2 + len(x) % 2 - 1) % 2.0
            return x[i]



#2

Might want to rethink that loop. It always returns on the first iteration.
You've also got some lines that have no effect on the program.
If you consider how you would compute a median manually for a sorted list, does that involve looping?
What does % do?


#3

Could you be a little more specific? I made some changes, now it looks like this:

def median(x):
    x = sorted(x)
    for i in range(len(x)):
        if len(x) / 2 == 1:
            x[i] == len(x) % 2
            return x
            
        else:
            x[i] == (len(x) % 2 + len(x) % 2 - 1) % 2.0
            return x

Now i get this: Oops, try again. median([1]) returned [1] instead of 1


#4

why are you using a loop? I don't see what purpose it serves. You just need the middle item(s) (len/2 for odd list, and len/2 + len/2-1)

I don't see why you would use a loop for it.

The moment a return keyword is reached, the function ends (even if it is in the middle of a loop)

% gives you remainder, just so know, i see you use it a lot, not sure why. to divide user the forward slash


#5

You have quite a lot of information that you don't seem to be considering.

To write a program you need to decide what events should take place to produce the desired effect. You have to convince yourself that those events lead up to what you want, and be able to motivate why each event need to happen.

A good place to start is to consider how you yourself would perform this task and analyze how you do it.

The first thing you may want to address is what the loop is meant to accomplish.

If you execute your code manually for a list, in your head, do you then end up with the median for that list?

If you did, then you execute it differently from Python itself. So you would then need to find out where the difference is and what you need to change so that your understanding and what it does is the same.


#6

Right now, your function is equivalent to this:

def median(x):
    if len(x) > 0:
        return sorted(x)

So what is the rest supposed to be doing? Find out if it really does that. What can you do to make the program explain to you what it is doing?

Decide what it should do.
Write code that corresponds to those actions.
Verify that the code does those actions.