for n in numlist:
Try this one
n = len(num)
num = sorted(num)
if n%2 == 1:
m = n/2
m = n/2
s = float ((num[m-1] + num[m]))/2
num = [1, 2, 3, 4, 5]
This works fine. Remember to indent
This worked for me, see below But the bit I'm not getting is:
mid = len(x) / 2
When I test it with some print statements based on five elements "[5,4,3,2,1]". I get the mid point as 2. Its like its rounding down, i.e
mid = 5 / 2
mid = 2
I use mid as my index to the above list and get the answer 3
Why is this?
Is my code faulty or is this expected functionality?
def median(y): x = sorted(y) mid = len(x) / 2 if len(x) % 2 != 0: #uneven number of elements return x[mid] else: #even number of elements dmid = mid - 1 result = float((x[dmid] + x[mid])) / 2 return result
5 / 2 = 2 because both 5 and 2 are integers. Therefore you get an integer as a result.
However, 5.0 / 2.0 = 2.5 This is because we are now dividing floats.
I hope that helps.