Median - an if/elif/else attempt


#1

Good afternoon. I have been skirting around this problem for a while. I felt I was getting close using the append() function but dropped that when I realised the answer was just one number. So simplified it to the code you see below. I THINK this should work but I cannot get it to run as the following message comes up:

" File "python", line 5
elif len(x)%2==0:
^
SyntaxError: invalid syntax "
Now this maybe one of those times I have overlooked the obvious. But please have a look and tell me where I am in error. Thank you.
The "else" phrase is for the events that have just one digit in ie not divisible by two with an integer remaining.

    x=sorted(x)
    if len(x)%2==1:
        x=(len(x/2.0)-1
    elif len(x)%2==0:
        x=((len(x)/2.0)-1)+(len(x/2.0))/2.0
    else:
        return x
print median



#2

def median(x):
    x=sorted(x)
    if len(x)%2==1:
        x=(len(x/2.0)-1
    elif len(x)%2==0:
        x=((len(x)/2.0)-1)+(len(x/2.0))/2.0
    else:
        return x
print median

#3

look at your parentheses on the line above the error message


#4

Thank you for your quick reply, I am not quite sure I follow what you are referring to. I have carefully looked at all the aspects, which usually mean I am over looking something.


#5

here:

x=(len(x/2.0)-1

look at your parentheses


#6

Ah yes wow, it is hard to find bugs isn't it!


#7

yep, its difficult

Everything resolved now?


#8

Everything except the problem of x==1, the equations fall down there. But I am excited to get that sorted as that issue will arise with the software I am planning on designing once I can do this language. If I still struggle and start crying I may ask for guidance.


#9

look at this math:

1 / 2 = 0
3 / 2 = 1
5 / 2 = 2
7 / 2 = 3
9 / 2 = 4

its the length of the list divided by two, perfectly gives the middle index


#10

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