Search code examples
pythonpython-3.x

python code to calculate median for a list as input


I have the following function:

def median(list):
  if list ==[]:
    return []

  elif len(list)==1:
    return list[0]

  else: 
    list= sorted(list)
    length= len(list)+1
    median=0

    if length%2==0:
            median= (list[length/2]+list[length/2-1])/2
    else:
            median= list[length-1/2]    
  return median

It gives me an error when I call it like this:

median([4, 5, 5, 4])

resulted in an error: list index out of range


Solution

  • I have modified your code and tested for a few cases.

    def median(list1):
       
       length= len(list1)
       
       if length <=0 :
           return None
       if (length)==1:
           return list1[length//2] 
       else: 
         list1= sorted(list1)
         median=0
     
         if length % 2 == 0:
                 median= (list1[length//2]+list1[length//2-1])/2
         else:
                 median= list1[length//2]    
       return median