-7

i am trying to print the median of three numbers but when the test case for example is the numbers 2,1,2 it gives none but when i try 2,2,1 it gives me the right answer which is 2, so how do i fix this code?

def median(a,b,c):
if a>b:
    if a>c:
        if b>c:
            return b
        else:
            return c
    elif c>a:
        if a>b:
            return a
        else:
            return b
elif b>a:
    if b>c:
        if a>c:
            return a
        else:
            return c
    elif c>b:
        if a>b:
            return a
        else:
            return b



elif a==c:
    return a

elif a==b:
    return a

elif b==c:
    return b

print(median(2,1,2))
Malouda
  • 107
  • 3
  • 10
  • 2
    A vast number of questions here on SO are about code that doesn't work the way the author wants it to. Using that as the title *makes your question meaningless*. Please create an actual question title. – Martijn Pieters Jun 10 '14 at 16:35
  • So, what's the question? How to find the median? Why it doesn't work? How to make it work with minimal changes? ... ? – amit Jun 10 '14 at 16:38
  • @shtuff.it This is not a dupe (probably), as the question is (likely) related to fixing the supplied code, and not how to do it in a generic way for arbitrary number of elements – amit Jun 10 '14 at 16:39
  • Only thing I would add to that @shtuff.it would be to pass in *args to the method and then cast it as a list with `list(args)` since it seems like he wants to be able to pass in multiple variables and not a list. That way it could suite his needs, however that would be how I would tackle the problem. – Bob Jun 10 '14 at 16:44
  • You shouldn't be trying to anticipate what order the parameters are in. You should take them how they come and sort them into the order you want and then process them. – kylieCatt Jun 10 '14 at 16:58

1 Answers1

0

Follow those values through your function:

def median(2, 1, 2):
    if 2 > 1: # yes
        if 2 > 2: # no
            ...
        elif 2 > 2: # also no
            ...
        # no 'else' here, and
    ... # other 'elif' choices never run
    # fall out of function - implicit 'return None'

You simply don't deal with that case!

The branching structure of your program is difficult to read and (clearly!) prone to error. Think more carefully about what you're trying to achieve - there's a much simpler approach.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334