15/15 median. is this code correct?

def median(lists):
  result = 0
  if len(lists) % 2 != 0:
    result = float(lists[len(lists)/2])
    result = float((lists[len(lists)/2]) + float(lists[(len(lists)/2) - 1])) / 2 
  return result

if not, please advice

if yes, how can i make it better?


Hi @methodrunner79483,

If the function produces the correct median for lists that contain odd as well as those that contain even numbers of elements, it is correct in that regard. You can test it with various examples to verify whether that is true.

Another issue is whether the function leaves the list that it is passed in its original unsorted form. It is true that you should perform a sort within the function, however, it is best for a function to leave the original object intact, unless one of the purposes of the function is to change that object.

Try this …

grades = [94, 95, 97, 96, 93]

Does calling the function change the order of the elements in grades?


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