15 median. getting problem

#1

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

why

def median(l):

``````if len(l)%2 == 0:
return (sorted(l)[(len(l)-2)/2] + sorted(l)[len(l)/2])/2
else:
return sorted(l)[(len(l)-1)/2]``````

print median([1,2,3,4])
print median([1,3,2])

#2

What have you done so far to solve this?

You might start my considering whether you agree with the error message, and then if you do you can start investigating how it got that result.. Or if you don't agree then the issue is in identifying the difference in what it does from what it should do, and you'd have to explain that

#3

my else statment is giving right answer but if is not. you can easly understand what have i done in my code.

#4

Sure but this is about your understanding So to give you a push forwards I need to know what your current thoughts are on the problem

I suggest splitting it up into smaller parts and putting them in variables. For example the sorted array, the index(es), the value(s) and then you can inspect those to see which operation didn't have the desired result

#5

finally give me sol.
finally give me sol.
finally give me sol.

#6

I don't understand what you mean to say by that.

#7

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

now tell me where is problem

def median(l):
x = sorted(l)

``````if len(x)%2 == 0:
m = len(x)/2

return (x[1] + x[2])/2
else:
return x[(len(x)-1)/2]``````

print median([4,5,5,4])
print median([1,3,2])

#8

sorry sorry. got it . i forgot float

#9

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