15.15 median


cant solve it, tried everything. below is my best try, plz help me

def median(l):
    s = sorted(l)
    ll = len(l)
    if ll % 2 == 0:
        findmid1 = ll/2
        return s[findmid1] 
        findmid2 = (ll/2)-1
        avg = (findmid1+findmid2)/2
        return avg


btw the error is:
" Oops, try again. median([1]) resulted in an error: local variable ‘findmid1’ referenced before assignment"


The error is caused by scope. Inside the else clause you’re using the variable findmid1 which it can’t access, because you created it in the if clause.
This is not the biggest error. The biggest error is your code logic. I’m not gonna tell you how to do it, because I would be giving the answer (which is no fun, right :smile:). Instead, I’ll give you a general way to go about solving these problems.

Write down cases

Write down all the boundary cases that you can think of and add the answer as well.
In this case, there are several boundary cases you could think of:

  1. len(l) is 0
  2. len(l) is 1
  3. len(l) is even
  4. len(l) is odd

Write down an example for each, together with the answer it should give.

Try to solve it like your algorithm would

For each example, write down the indices below it and see if you’re getting the answers you want to get. Don’t forget to write down what operation you’re using (for instance dividing by 2).

Write down the code

Try to just follow the general steps you took in solving it by hand.


If it still doesn’t work, debug! Add as many print statements as you might need to solve the problem and to see what’s wrong. Give your examples as arguments and check if it does the right thing.

Following these steps, you should be able to solve it. If you come upon something you can’t solve, feel free to ask!

Games with python

Lol man I had so much problems, but the biggest one was that in the if statment I did == 0 instead of !=0 (got confused with odd and even, dunno why), fixed more minor problems and I got it! its working, thx for helping