kindly identify the error:

def median(numbers):
a = sorted(numbers)
x = len(a)
for number in a:
if x % 2 == 0:
add = a[x/2] + a[(x/2) + 1]
return add / 2.0
add = a[x + 1]
return add / 2.0

print median([1,7,9,74,2])


No loop is needed. We only need three things:

  1. a sorted sample list
  2. the length
  3. the middle index

For an odd length list, the middle index is the result of,

int(n / 2)

where n is the length of the sample. Return the value in the element at that index.

In an even length sample, the above is the higher of the middle pair, so the other value will be at the value, minus 1. Return the average of the two values.


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