Code


#1



median problem


as per the error the new list >inc< is not sorted
"Oops, try again.median([6, 8, 12, 2, 23]) returned 12 instead of 8"


i wanted a proper result


def median(ina):
   inc = sorted(ina)
   k = len(inc)
   if k == 1:
       return inc[k - 1]
   if k % 2 == 0:
       return ((inc[k / 2] + inc[k / 2 - 1]) / 2.0)
   if k % 2 != 0:
       return inc[(k + 1)/ 2]


#2

The list in the error is not sorted because it is the input(ina) not inc.

For lists of odd length you return inc[(k +1) /2 ].
Consider a this sorted list of length 3: [1, 2, 3]

(k + 1) / 2 = (3 + 1) / 2 = 2

Because the first element is at index 0 the element at index 2 is the last, not the middle element.

The middle element is at index (k -1) / 2.


#3

thank you very much, it solved my problem.


#4

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